我是java的新手,我正在尝试编写一个代码,显示他们正确的问题数量,而不是他们每个人都正确。当我尝试运行它时,我无法显示它们正确的问题数量。例如,我希望它说'#34;你有5个问题中的4个正确!",取决于他们有多少正确。这就是我到目前为止所做的:
import java.util.Scanner;
public class Addition {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int count = 0;
while (count < 5){
int number1 = (int)(Math.random() * 100);
int number2 = (int)(Math.random() * 100);
System.out.println("What is " + number1 + " + " + number2 + "?");
count++;
int answer = number1 + number2;
int guess = sc.nextInt();
boolean correct = guess == answer;
if (guess == answer){
}
System.out.println("You got " + correct + " correct");
}
}
}
答案 0 :(得分:0)
您的逻辑需要稍作修改。
int correctAnswer = 0; // this is a new variable you have to introduce before while (count < 5){
if (guess == answer){
correctAnswer++;
}
// This line should be outside of while loop as well..
System.out.println("You got " + correctAnswer + " out of " + count + " questions correct");
答案 1 :(得分:0)
您的代码中存在两个问题: (1)没有正确答案的计数; (2)完成后不打印。 您做在测试过程中有打印,但那不是您说要打印的时候。尝试这两个更改:在if语句中计数并在循环之后打印。
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int count = 0;
while (count < 5){
...
boolean correct = guess == answer;
if (guess == answer){
correct++;
}
}
System.out.println("You got " + correct + " out of " + count " questions correct");
}