创建一个程序,该程序将根据选择的问题类型询问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));
}
}
}
答案 0 :(得分:1)
我添加了静态变量,它是您要询问用户的问题数量(最终int NUM_PROBLEMS = 10)。
您的while循环在if语句之前结束。我将while循环的结束括号移到了末尾,更改了while循环标题,以确保当有10个问题被问到并且每次问一个问题时在底部递增的problemCount时while循环都停止了。
{
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++;
}
}