为什么扫描程序在循环java中没有请求try-catch中的其他输入

Uma*_*nth 3 java double exception-handling java.util.scanner

假设我需要继续询问用户,直到他进入double.

我做的是我使用了一个while循环并检查是否有异常.

如果有异常,我会去询问下一个输入.

double bal = 0;
Scanner sc = new Scanner(System.in);
while (true) {
    try {
        System.out.println("Enter the balance");
        bal = sc.nextDouble();
        break;
        } catch (Exception e) {
          System.out.println("That isn't a number");
    }
}
System.out.println("Bal is " + bal);
sc.close();
Run Code Online (Sandbox Code Playgroud)

但是如果我输入一个非double,那么它不会要求下一个输入,继续打印以无限循环结束的那两行.

Enter the balance
XYZ
That isn't a number
Enter the balance
That isn't a number
Enter the balance
That isn't a number
Enter the balance
That isn't a number
....
Run Code Online (Sandbox Code Playgroud)

我错过了什么?

Zar*_*wan 11

您需要通过调用sc.next()catch块来丢弃流中的先前输入.遗憾的是,当输入失败时,扫描仪不会自动执行此操作.


Tag*_*eev 5

使用sc.next()丢弃错误输入:

while (true) {
    try {
        System.out.println("Enter the balance");
        bal = sc.nextDouble();
        break;
    } catch (InputMismatchException e) {
        System.out.println("That isn't a number");
        sc.next();
    }
}
Run Code Online (Sandbox Code Playgroud)

我还建议捕获特定的异常(InputMismatchException在这种情况下).这样,"That isn't a number"如果出现其他问题,您将不会错误地打印(例如,标准输入流已关闭).