如果我这样称呼:
math a = new math ();
for (x=0; ×<5;x++){
a.addition ();
}
在主要班级^
import java.util.*;
public class math
{
Scanner scan = new Scanner(System.in);
Random rand = new Random();
private int num1 = rand.nextInt(100);
private int num2 = rand.nextInt(100);
private int correctanswers = 0;
public void addition(){
System.out.println(num1 + " + " + num2 + " = ");
int answer = scan.nextInt();
if (answer == (num1 + num2)){
correctanswers++;
}
}
public int getcorrectanswers(){
return correctanswers;
}
}
每次绕过&#39;对于&#39;来说,我得到的是相同的数字。循环(5次)我想知道的是,每当它越过&#39;对于&#39;当a.addition()被调用时循环 例如: 每次打印5 + 7而不是每次打2个不同的数字显然我想要的是5 + 2然后4 + 50等。
答案 0 :(得分:4)
那是因为
private int num1 = rand.nextInt(100);
private int num2 = rand.nextInt(100);
是数学对象的字段。两者都在new math()
上初始化一次。
将它们作为局部变量放在addition
方法中:
public void addition(){
int num1 = rand.nextInt(100);
int num2 = rand.nextInt(100);
System.out.println(num1 + " + " + num2 + " = ");
int answer = scan.nextInt();
if (answer == (num1 + num2)){
correctanswers++;
}
}
答案 1 :(得分:0)
每次调用addition()时,数学类中的random int都是相同的。 添加到'添加' - &gt; num1 = r.nextInt() 获取'num1'的新随机数