如何使此循环 10 次然后结束



创建一个程序,该程序将根据选择的问题类型询问 10 个问题。我如何让这个问题只问 10 次,并在每个问题后显示它是错的还是对的?

我尝试使用 for(int i=1;i<=10;i++(,但它在每个答案之后都不显示答案是对还是错

{
int userType, probType, level, op1=0, op2=0, correctAnswer, studentAnswer=0, numCorrect=0;
Scanner input = new Scanner(System.in);
boolean playAgain;
System.out.println("Problem Type 1 is sum, 2 is difference, 3 is product, 4 is quotient, and 5 is random. What problem type do you want?");
probType = input.nextInt();
System.out.println("You selected " + probType + ". What level from 1 to 3 do you want to play? ");
level = input.nextInt();
while(probType == 1){
op1 = (int)(Math.random() * 9);
op2 = (int)(Math.random() * 9);
System.out.println("What is " + op1 + "+" + op2 + "?");
studentAnswer = input.nextInt();
}if(studentAnswer == op1 + op2){
System.out.println(studentAnswer + " is correct");
numCorrect++;
}else{
System.out.println(studentAnswer + " is wrong. The right answer is " + (op1 + op2));
}
}
}

我添加了静态变量,即您希望向用户提出的问题数量(最终整数NUM_PROBLEMS = 10(。

您的 while 循环在 if 语句之前结束。我已经将 while 循环的右括号移到了末尾,更改了 while 循环标题以确保 while 循环在提出 10 个问题时停止,并在底部递增问题每次提出问题时计数。

{
int userType, probType, level, op1=0, op2=0, correctAnswer, studentAnswer=0, numCorrect=0, problemCount=1;
final int NUM_PROBLEMS = 10;
Scanner input = new Scanner(System.in);
boolean playAgain;
System.out.println("Problem Type 1 is sum, 2 is difference, 3 is product, 4 is quotient, and 5 is random. What problem type do you want?");
probType = input.nextInt();
System.out.println("You selected " + probType + ". What level from 1 to 3 do you want to play? ");
level = input.nextInt();
while(probType == 1 && problemCount <= NUM_PROBLEMS){
op1 = (int)(Math.random() * 9);
op2 = (int)(Math.random() * 9);
System.out.println("What is " + op1 + "+" + op2 + "?");
studentAnswer = input.nextInt();
if(studentAnswer == op1 + op2){
System.out.println(studentAnswer + " is correct");
numCorrect++;
}else{
System.out.println(studentAnswer + " is wrong. The right answer is " + (op1 + op2));
}
problemCount++;
}
}

最新更新