代码不退出 while 循环(试图捕获异常)

Code not exiting while loop (trying to catch exceptions)

我在尝试学习 try / catch 异常处理的同时编写了非常简单的代码 (n1 / n2 = sum)。

我有一个 do / while 循环,它应该在 运行 成功时使 x = 2。如果不是,x = 1,用户输入可以再次输入。

代码编译并且 运行s 但如果我尝试,例如 n1 = 10,n2 = Whosebug,捕获异常的 prinln 永远 运行s!

为什么循环卡住了?

提前致谢

import java.util.*;

public class ExceptionHandlingMain {
    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        int x = 1; // x originally set to 1
        do { // start of do loop
            try {
                System.out.println("Enter numerator: ");
                int n1 = input.nextInt();

                System.out.println("Enter divisor");
                int n2 = input.nextInt();

                int sum = n1 / n2;

                System.out.println(n1 + " divided by " + n2 + " = " + sum);
                x = 2; 
// when the code is completed successfully, x = 2 and do / while loop exits

            } catch (Exception e) {
                System.out.println("You made a mistake, moron!");
            }
        } while (x == 1); 
    }
}

那是因为您正在按 return 键 post 输入号码。

我建议您添加 input.nextLine(); 调用,这样您在从 Scanner 读取输入后也可以使用 return 键。

因此使用 nextInt api,当您键入时:

 123<return key>

nextInt 只会将 123 作为字符串提取并将其转换为数字,并保留 return 关键部分。

在您的 catch 块中添加 input.nextLine() 以清除读取的行。

谢谢@barak manos(以及其他回复者)

添加

input.nextLine(); 

紧接着

System.out.println("You made a mistake, moron!");

清除输入流并允许用户输入新数据。

引用: 答案改编自 用户:user3580294