我的程序没有任何语法错误,只有逻辑。输出应显示每个问题是否正确或不正确,并显示有多少 测验结果正确,测验结束时有多少不正确。
import java.util.Scanner;
public class SubtractionQuiz {
public static void main(String[] args) {
//Declare and initialize variables
final int NUMBER_OF_QUESTIONS = 10;
int correctCount = 0;
int count = 0;
int incorrect = 0;
int temp;
Scanner input = new Scanner(System.in);
while (count < NUMBER_OF_QUESTIONS) {
// Declare and initialize two random numbers
int number1 = (int)(Math.random()*10);
int number2 = (int)(Math.random()*10);
if (number1 < number2) {
temp = number1;
number1 = number2;
number2 = temp;
// Prompt the question
System.out.print("What is " + number1 + " - " + number2 + "? ");
int answer = input.nextInt();
if (number1 - number2 == answer)
System.out.println("Correct!");
correctCount++;
}
else
System.out.println("Incorrect");
incorrect++;
count++;
}
System.out.printf("You got %d correct and %d incorrect!", correctCount, incorrect);
}
}
答案 0 :(得分:0)
至少,你的牙套会掉下来。没有左大括号,只有if
或else
之后的第一行才是条件的一部分。
if (number1 - number2 == answer) // <--- should there be a "{" here?
System.out.println("Correct!");
correctCount++;
}
else // <--- need a "{" here ?
System.out.println("Incorrect");
incorrect++;
count++;
}
建议清理缩进以保持一致,以便您可以更清楚地看到此问题。
答案 1 :(得分:0)
你没有为if和else块添加开括号(包含多于1个语句),你也必须稍微重构代码。 在此计划的评论中找到我的补充
import java.util.Scanner;
public class SubtractionQuiz {
public static void main(String[] args) {
//Declare and initialize variables
final int NUMBER_OF_QUESTIONS = 10;
int correctCount = 0;
int count = 0;
int incorrect = 0;
int temp;
Scanner input = new Scanner(System.in);
while (count < NUMBER_OF_QUESTIONS) {
// Declare and initialize two random numbers
int number1 = (int)(Math.random()*10);
int number2 = (int)(Math.random()*10);
if (number1<number2) {
temp = number1;
number1 = number2;
number2 = temp;
// Prompt the question
System.out.print("What is " + number1 + " - " + number2 + "? ");
int answer = input.nextInt();
if (number1 - number2 == answer) { // adding an opening brace here
System.out.println("Correct!");
correctCount++;
} else { // adding an opening brace here
System.out.println("Incorrect");
incorrect++;
}
count++;
}
}
System.out.printf("You got %d correct and %d incorrect!\n", correctCount, incorrect); //Moving this outside the while loop
} //closing braces for main
} //closing braces for class