【问题标题】:random operator for math quiz [duplicate]数学测验的随机运算符 [重复]
【发布时间】:2020-04-18 08:24:14
【问题描述】:

我正在尝试生成随机运算符以使随机问题具有随机运算符,请帮助

public void generateNewAddQuestion () {
        Random rand = new Random();
        int a = rand.nextInt(21);
        int b = rand.nextInt(21);
        int c =0;

        sumTextView.setText(Integer.toString(a) + "+" + Integer.toString(b));
        locationOfCorrecAnswer = rand.nextInt(4);
        answers.clear();
        String[] operators = {"+", "-", "x", "/"};

        int incorrectAnswer;

        for (int i=0; i < 4; i++) {
            if (i == locationOfCorrecAnswer) {
                answers.add(a+b);
                sumTextView.setText(Integer.toString(a)+"+"+Integer.toString(b));
            }
            else {
                incorrectAnswer = rand.nextInt(41);
                while(incorrectAnswer == a+b) {
                    incorrectAnswer = rand.nextInt(41);
                }
                answers.add(incorrectAnswer);
            }
        }
        button2.setText(Integer.toString(answers.get(0)));
        button3.setText(Integer.toString(answers.get(1)));
        button4.setText(Integer.toString(answers.get(2)));
        button5.setText(Integer.toString(answers.get(3)));
    }

【问题讨论】:

  • 我还有四个用于用户界面的按钮,我只需要一种使操作员更加动态的方法,目前,添加工作正常
  • 在有人完全不理我并说以前有人问过这个问题之前,我已经完成了我的研究,从我的角度来看,我刚刚检查的那些与这个不相似,提前谢谢
  • 与其防御,不如列出相似但不重复的问题。

标签: java android


【解决方案1】:

您需要使用operators[rand.nextInt(4)] 来获取随机运算符,例如

import java.util.Random;

public class Main {
    public static void main(String[] args) {
        String[] operators = { "+", "-", "x", "/" };
        Random rand = new Random();
        System.out.println(operators[rand.nextInt(4)]);
    }
}

如果您执行此代码,它将每次打印一个随机运算符。

[更新]

这就是您需要在程序中使用该解决方案的方式:

String[] operators = {"+", "-", "x", "/"};
int oprIndex = rand.nextInt(4);
sumTextView.setText(Integer.toString(a) + operators[oprIndex] + Integer.toString(b));

稍后在您的程序中,您将需要使用oprIndex 来查找已将哪个运算符设置为sumTextView,然后您可以执行相应的算术运算,例如

switch (operators[oprIndex]) {
case "+":
    System.out.println("Pocessing addition");
    break;
case "-":
    System.out.println("Pocessing subtraction");
    break;
case "x":
    System.out.println("Pocessing multiplication");
    break;
case "/":
    System.out.println("Pocessing division");
    break;
}

【讨论】:

  • 您好,您对我如何使用您建议的代码以便每次使用不同的运算符生成新问题有什么建议吗?我的代码唯一的缺点是每次只能生成随机数,但只能使用加法运算符。我希望生成的新问题有减法或乘法
  • @cams - 我已经发布了更新。如果您还有任何疑问,请告诉我。
  • if (oprIndex == '+'){ if(i == locationOfCorrecAnswer){} }else if(oprIndex == '-'){ locationOfCorrecAnswer = a-b; }else if(oprIndex == ''){ locationOfCorrecAnswer = ab; }
  • 我试着用这种方式比较它并得到一个错误,这是我的最后一个问题,谢谢 inadvance
  • 你说你更新它是为了让我知道如何使用 oprindex?同时,我正在尝试了解如何使用 switch 语句来代替
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-03-07
  • 2022-10-07
  • 2013-01-10
  • 1970-01-01
  • 2019-07-03
  • 1970-01-01
  • 2015-05-08
相关资源
最近更新 更多