更改随机运算符或变量

Change random operator or variable

我在编程中有一个作业 class。事情是这样的,我必须制作一个程序,让用户输入他想做多少练习。然后,他用 1-10 的随机数和随机运算符解决简单的计算问题。最后应该写出他答对了多少,错了多少。它还应写入任务的运行时间。 我做了一些工作,但是当我为一个操作分配一个随机值时

int operation = (int)(Math.random()*3)+1;

或数字 a 和 b

int a = (int)(Math.random()*10); int b = (int)(Math.random()*10);

当我第二次或第三次选择我的任务时,我总是得到相同的数字和运算符(因为我使用了循环)。有没有办法在程序中更改相同的初始化变量或运算符。例如 int a=(int)(Math.Random()*10) 在开始时被初始化为 3,然后程序再次循环将其初始化为不同的数字,例如 6。我的问题还有其他解决方案吗? 这是我的全部代码,现在:

    import java.util.*;
    import javax.swing.JOptionPane;
    public class RandomChar {


public static void main(String[] args) {

    char op= ' ';
    int operation = (int)(Math.random()*3)+1;

    int a = (int)(Math.random()*10);
    int b = (int)(Math.random()*10);
    String s;
    int correct = 0, incorrect=0;

    s = JOptionPane.showInputDialog("How many exercises do you want?");
    int num = Integer.parseInt(s);

    long tStart = System.currentTimeMillis();

    while(num>0){

        if(operation==1)
        op='+';
    else if(operation==2)
        op='-';
    else if(operation==3)
        op='*';

    String str1 = JOptionPane.showInputDialog(a+" "+op+" "+b+" = ");
    int num1 = Integer.parseInt(str1);

    if(op=='+'){
    if(a+b==num1)
        correct++;
    else
        incorrect++;
    }else if(op=='-'){
        if(a-b==num1)
            correct++;
        else
            incorrect++;
    }else if(op=='*'){
        if(a*b==num1)
            correct++;
                    else
            incorrect++;
    }
    num--;
    }

    long tEnd = System.currentTimeMillis();
    long tOverral = tEnd - tStart;
    double elapsedSeconds = tOverral / 1000.0;
    System.out.println("Correct: "+correct);
    System.out.println("Incorrect: "+incorrect);
    System.out.println("Elapsed seconds: "+ elapsedSeconds);


}

}

只需将随机数的计算和运算符移到您的 while 循环中即可。其实你计算一次。

while (num > 0) {
    int operation = (int) (Math.random() * 3) + 1;

    int a = (int) (Math.random() * 10);
    int b = (int) (Math.random() * 10);
    ...
}

所以您在任何练习中都会有新的数字和运算符。