Java 尝试捕捉循环问题
在下面的代码中,我希望程序通过try catch循环,以允许用户重新输入答案进行首次添加,如果他们提供了无效的输入,即字母而不是int。当前代码显示catch语句,但也继续通过程序,并显示System.out.PrintLn对不起,不正确,请再次猜测;来自if else语句,这是我不想要的。有人能帮我解决这个问题吗?非常感谢Java 尝试捕捉循环问题,java,if-statement,try-catch,do-while,Java,If Statement,Try Catch,Do While,在下面的代码中,我希望程序通过try catch循环,以允许用户重新输入答案进行首次添加,如果他们提供了无效的输入,即字母而不是int。当前代码显示catch语句,但也继续通过程序,并显示System.out.PrintLn对不起,不正确,请再次猜测;来自if else语句,这是我不想要的。有人能帮我解决这个问题吗?非常感谢 public static void add() { // Setting up random Random random = n
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);
错误在这里:
while(correctAnswer=false)
你需要
while(correctAnswer==false)
你得到的是一个false到correctAnswer的赋值-一个总是false的表达式,所以循环永远不会继续。更常见的编写A==false的方法是!a、 因此,我会将循环条件更正为
while(!correctAnswer)
读起来更流利
当然,现在您需要在循环的顶部设置correctAnswer=true,以避免无限次的迭代。这修复了第一部分,但是更改whilecorrectAnswer=false和whilecorrectAnswer==false将导致一个无休止的循环,因为correctAnswer永远不会更改为true,而这已经解决了我的问题!你所说的无限迭代到底是什么意思?我看到代码可以工作,但不确定具体如何工作?@RNI2013由于您从未将correctAnswer设置为true,因此无法退出内部do/while循环。您应该添加correctAnswer=true;在循环的顶端解决这个问题。是的,已经解决了。谢谢你,我现在意识到了无限循环!