#java #android #arrays #operators
Вопрос:
общедоступный класс MainActivity расширяет совместимость приложений {
Button startButton;
ArrayList<Integer> answers=new ArrayList<Integer>();
int LocationOfRightAnswer;
TextView resultTextView;
TextView pointText;
Button button1;
Button button2;
Button button3;
Button button4;
int score=0;
int numberofquestions = 0;
TextView sumText;
TextView timertext;
RelativeLayout game;
Button playAgain;
public void playAgain(View view) {
score = 0;
numberofquestions = 0 ;
timertext.setText("30s");
pointText.setText("0/0");
resultTextView.setText("");
playAgain.setVisibility(View.INVISIBLE);
generateQuestion();
new CountDownTimer(30100,1000) {
@Override
public void onTick(long millisUntilFinished) {
timertext.setText(String.valueOf(millisUntilFinished / 1000) "s");
}
@Override
public void onFinish() {
playAgain.setVisibility(View.VISIBLE);
timertext.setText("0s");
resultTextView.setText("Your Score is " Integer.toString(score) "/" Integer.toString(numberofquestions));
}
}.start();
}
public void generateQuestion() {
Random random = new Random();
int a = random.nextInt(21);
int b = random.nextInt(21);
char[] ops = {' ' , '-' ,'*', '/'};
int l = random.nextInt(3) ;
sumText.setText(Integer.toString(a) " " Integer.toString(b) );
LocationOfRightAnswer = random.nextInt(4);
answers.clear();
int incorrectAnswer;
for (int i=0; i<4; i ) {
if (i == LocationOfRightAnswer) {
answers.add(a b);
}else {
incorrectAnswer = random.nextInt(41);
while (incorrectAnswer == a b) {
incorrectAnswer = random.nextInt(41);
}
answers.add(incorrectAnswer);
}
}
button1.setText(Integer.toString(answers.get(0)));
button2.setText(Integer.toString(answers.get(1)));
button3.setText(Integer.toString(answers.get(2)));
button4.setText(Integer.toString(answers.get(3)));
}
public void chooseAnswer(View view) {
if (view.getTag().toString().equals(Integer.toString(LocationOfRightAnswer))) {
score ;
resultTextView.setText("Correct");
} else {
resultTextView.setText("Wrong!");
}
numberofquestions ;
pointText.setText(Integer.toString(score) "/" Integer.toString(numberofquestions));
generateQuestion();
}
public void start (View view) {
startButton.setVisibility(View.INVISIBLE);
game.setVisibility(View.VISIBLE);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startButton =(Button) findViewById(R.id.startButton);
sumText = (TextView) findViewById(R.id.sumTextView);
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button3 = (Button) findViewById(R.id.button3);
button4 = (Button) findViewById(R.id.button4);
resultTextView = (TextView) findViewById(R.id.resultTextView);
pointText = (TextView) findViewById(R.id.pointsTextView);
timertext = (TextView) findViewById(R.id.timerTextView);
playAgain = (Button) findViewById(R.id.playAgain);
game = (RelativeLayout) findViewById(R.id.gamelayout) ;
playAgain(findViewById(R.id.playAgain));
}
}
пожалуйста, помогите мне настроить мой код так, чтобы приложение могло использовать всех операторов вместо простого добавления. Я пытался это сделать, но мне удалось создать только список массивов для операторов, но я не смог найти способ изменить код, чтобы включить все операторы.
Ответ №1:
Попробуйте это:
ArrayList<Double> answers=new ArrayList<Double>();
public void generateQuestion() {
Random random = new Random();
int a = random.nextInt(21);
int b = random.nextInt(21);
char[] ops = {' ' , '-' ,'*', '/'};
int l = random.nextInt(3) ;
char op = ops[random.nextInt(4)];
double correctAns=0;
switch(op){
case ' ' : correctAns = a b;
break;
case '/' : correctAns = (double)a/b;
break;
case '*' : correctAns = a*b;
break;
case '-' : correctAns = a-b;
break;
}
sumText.setText(Integer.toString(a) op Integer.toString(b) );
LocationOfRightAnswer = random.nextInt(4);
answers.clear();
int incorrectAnswer;
for (int i=0; i<4; i ) {
if (i == LocationOfRightAnswer) {
answers.add(correctAns);
}else {
incorrectAnswer = random.nextInt(41);
while (incorrectAnswer != correctAns) {
incorrectAnswer = random.nextInt(41);
}
answers.add((double)incorrectAnswer);
}
}
button1.setText(Double.toString(answers.get(0)));
button2.setText(Double.toString(answers.get(1)));
button3.setText(Double.toString(answers.get(2)));
button4.setText(Double.toString(answers.get(3)));
}
- измените
ArrayList<Integer> answers=new ArrayList<Integer>();
наArrayList<Double> answers=new ArrayList<Double>();
(int/int
может бытьdouble
) - создайте
double
переменную, содержащую правильный ответ (int/int
может быть adouble
) - выберите операцию случайным образом.
- используется
switch
для определения того, какая операция необходимаa
иb
в случае, если выбрана каждая операция. - установите для текста значение
Integer.toString(a) op Integer.toString(b)
вместоInteger.toString(a) " " Integer.toString(b)
- поменять
a b
местами наcorrectAns
Комментарии:
1. Ответы.добавить(корректно); не работает, говорят, что он должен быть инициализирован
2.
ArrayList<Double> answers=new ArrayList<Double>();
используйте это вместоArrayList<Integer> answers=new ArrayList<Integer>();
3. он говорит мне добавить ветвь «по умолчанию» в оператор «переключатель», который инициализирует «корректАны»
4. @ЗухайрАларакха Ох. в этом нет необходимости, так как в любом случае
correctAns
будет определено. В любом случае, я изменил его. просто инициализируйтеcorrectAns
значение 0 см. Обновление