在下面的代码中,我希望程序通过try catch
循环,以允许用户在输入无效输入(即字母而不是int)时重新输入第一个添加的答案。目前代码显示catch语句,但也会继续执行该程序,并显示if if语句中的System.out.println("Sorry incorrect, please guess again");
,我不想要。有人可以帮我解决这个问题吗?非常感谢!
public static void add() {
// Setting up random
Random random = new Random();
// Declaring Integers
int num1;
int num2;
int result;
int input;
input = 0;
// Declaring boolean for userAnswer (Defaulted to false)
boolean correctAnswer = false;
do {
// Create two random numbers between 1 and 100
num1 = random.nextInt(100);
num1++;
num2 = random.nextInt(100);
num2++;
do{
// Displaying numbers for user and getting user input for answer
System.out.println("Adding numbers...");
System.out.printf("What is: %d + %d? Please enter answer below",
num1, num2);
result = num1 + num2;
try {
input = scanner.nextInt();
} catch (Exception ex) {
// Print error message
System.out.println("Invalid number entered for addition...");
// flush scanner
scanner.next();
correctAnswer = false;
}
}while(correctAnswer=false);
// Line break for code clarity
System.out.println();
// if else statement to determine if answer is correct
if (result == input) {
System.out.println("Well done, you guessed corectly!");
correctAnswer = true;
} else {
System.out.println("Sorry incorrect, please guess again");
correctAnswer=false;
}
} while (!correctAnswer);
答案 0 :(得分:0)
错误在于:
while(correctAnswer=false)
你需要
while(correctAnswer==false)
您所拥有的是false
到correctAnswer
的分配 - 一个始终为false
的表达式,因此循环永远不会继续。写a==false
的更常见方法是!a
,所以我会将循环条件更正为
while(!correctAnswer)
更“流利”地阅读。
当然,现在需要在循环顶部设置correctAnswer = true
以避免无限次迭代。