Как случайным образом генерировать случайные операторы в Android studio

#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)));


}
 
  1. измените ArrayList<Integer> answers=new ArrayList<Integer>(); на ArrayList<Double> answers=new ArrayList<Double>(); ( int/int может быть double )
  2. создайте double переменную, содержащую правильный ответ ( int/int может быть a double )
  3. выберите операцию случайным образом.
  4. используется switch для определения того, какая операция необходима a и b в случае, если выбрана каждая операция.
  5. установите для текста значение Integer.toString(a) op Integer.toString(b) вместо Integer.toString(a) " " Integer.toString(b)
  6. поменять a b местами на correctAns

Комментарии:

1. Ответы.добавить(корректно); не работает, говорят, что он должен быть инициализирован

2. ArrayList<Double> answers=new ArrayList<Double>(); используйте это вместо ArrayList<Integer> answers=new ArrayList<Integer>();

3. он говорит мне добавить ветвь «по умолчанию» в оператор «переключатель», который инициализирует «корректАны»

4. @ЗухайрАларакха Ох. в этом нет необходимости, так как в любом случае correctAns будет определено. В любом случае, я изменил его. просто инициализируйте correctAns значение 0 см. Обновление