我被困在我回到的部分:“是” - 我想继续或“不” - 我想退出。
我知道我需要显示一个if?仅在退出程序时才显示结果
//Input your display and questions:
int num1 = (int) (Math.random() * 10 +1);
int num2 = (int) (Math.random() * 10 + 1);
int answer = 0;
int correctCount=0;
int count= 0;
//Scanner object input
Scanner input = new Scanner(System.in);
//Swap numbers if number2 is bigger than number 1
if (num1 < num2) {
int temp = num1;
num1 = num2;
num2 = temp;
}
//OUTPUT DISPLAY QUESTION: What is num1 + num2 = ?
System.out.print("What is "+num1 + " * " + num2 + " = ");
answer = input.nextInt();
//If answer is correct display: Good Job! Your got it right
if (answer == (num1 * num2))
{
System.out.println("Good job! You got it right!\n");
correctCount++; //Increases correct count for answer correct!
}
else
System.out.println("You got it wrong, try again!\n" +num1 + " * " +num2+ " should be " + (num1 * num2));
count++;
System.out.print("Enter Y to continue or N to exit: \n"); //Do you want to continue
System.out.println("\nYou got " +correctCount+ " out of "+count + " answer correct"); //Displays Correct with total# of questions
}
}
答案 0 :(得分:0)
您只需使用while
循环即可使应用循环,直到用户输入y
以外的字符。
另外,尝试使用try-with-resource
来避免scanner
对象
像这样:
public static void main(String[] args) {
// Input your display and questions:
int answer = 0;
int correctCount = 0;
int count = 0;
String continueStr = "yes";
try (Scanner input = new Scanner(System.in)) {
while (continueStr.equalsIgnoreCase("yes")) {
// Scanner object input
int num1 = (int) (Math.random() * 10 + 1);
int num2 = (int) (Math.random() * 10 + 1);
// Swap numbers if number2 is bigger than number 1
if (num1 < num2) {
int temp = num1;
num1 = num2;
num2 = temp;
}
// OUTPUT DISPLAY QUESTION: What is num1 + num2 = ?
System.out.print("What is " + num1 + " * " + num2 + " = ");
answer = input.nextInt();
input.nextLine();
// If answer is correct display: Good Job! Your got it right
if (answer == (num1 * num2)) {
System.out.println("Good job! You got it right!\n");
correctCount++; // Increases correct count for answer correct!
} else {
System.out.println("You got it wrong, try again!\n" + num1 + " * " + num2 + " should be " + (num1 * num2));
}
count++;
System.out.print("\nEnter Yes to continue or No to exit: \n"); // Do you want to continue
continueStr = input.nextLine();
}
System.out.println("\nYou got " + correctCount + " out of " + count + " answer correct"); // Displays Correct with total# of questions
}
}