gpt4 book ai didi

java - 如何让这个循环10次然后结束

转载 作者:行者123 更新时间:2023-11-30 05:27:35 25 4
gpt4 key购买 nike

创建一个程序,根据选择的问题类型询问 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));
}
}
}

最佳答案

我添加了静态变量,它是您希望向用户询问的问题数量(最终 int NUM_PROBLEMS = 10)。

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

{
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++;
}
}

关于java - 如何让这个循环10次然后结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58252363/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com