2 回答
TA贡献1111条经验 获得超0个赞
您在循环中获得的数字不应与您在 while(...) 条件中使用的数字存储在同一变量中。在这种情况下,您使用了 ans。在下面的示例中,我为数学答案和循环中迭代的次数设置了单独的变量。您遇到的另一个问题是您没有将结果消息传递给 showMessageDialog(..) 方法。
import javax.swing.JOptionPane;
import java.util.Random;
import java.util.Scanner;
public class MathQuiz {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random obj = new Random();
String timesString = JOptionPane.showInputDialog(null,"How many problems would you like to solve?");
int timesInt = Integer.parseInt(timesString); // answer from question
int counter = 0; //counts total math problems
while (counter != timesInt) {
counter++;
int num1 = obj.nextInt(10);
int num2 = obj.nextInt(10);
int rand = num1 + num2;
String answerString = JOptionPane.showInputDialog(num1 + "+" +num2);
int answerInt = Integer.parseInt(answerString);
JOptionPane.showMessageDialog(null, answerInt == rand ? "Correct" : "Incorrect");
}
}
}
TA贡献1815条经验 获得超6个赞
以下是您的代码中的问题: 计算值后没有显示结果。不是每次都生成随机数。
public class MathQuiz {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String response = JOptionPane.showInputDialog(null,"How many problems would you like to solve?");
int noOfTimes = Integer.parseInt(response); // answer from question
String result= null;
for (int counter = 0; counter < noOfTimes; counter++) {
Random obj = new Random();
int num1 = obj.nextInt(10);
int num2 = obj.nextInt(10);
int rand = num1 + num2;
int answer = Integer.parseInt(JOptionPane.showInputDialog(num1 + "+" +num2));
if (answer == rand){
result= "Correct";
}else {
result= "Incorrect";
}
JOptionPane.showMessageDialog(null, result);
}
}
}
添加回答
举报