无限循环当在try-catch块中捕获InputMidmatchException时

Kam*_* K. 3 java exception-handling try-catch infinite-loop java.util.scanner

我一直在无限循环中捕获我的代码.

它没什么可提升的,但我无法理解我的生活!

有人请帮忙

我只是重新创建了特定的错误,没有我在实际程序中的所有if语句.

    package bs;

    import java.util.InputMismatchException;
    import java.util.Scanner;

    public class bs {

        public static void main(String[] args) {

            Scanner sc = new Scanner(System.in);

            boolean continueVar = true;

            while (continueVar) {

                try {
                    System.out.println("Enter Something");
                    int input = sc.nextInt();

                } catch (InputMismatchException i) {
                    System.out.println("What the f***?");
                    continueVar = true;
                }
            }


        }
    }
Run Code Online (Sandbox Code Playgroud)

捕获输入不匹配异常时会发生无限循环.我认为它至少会要求用户重新输入他们的输入,但不是这样做,而是继续循环,如下所示:

    run:
    Enter Something
    df
    What the f***?
    Enter Something
    What the f***?
    Enter Something
    What the f***?
Run Code Online (Sandbox Code Playgroud)

它的行为就像只是忽略扫描仪对象sc?!

Tho*_*mas 5

不会跳过扫描仪,它只是从输入的开始处开始.来自JavaDoc:

如果翻译成功,扫描仪将超过匹配的输入.

这意味着如果转换不成功,扫描仪将无法前进.因此,您必须使用just手动跳过不正确的输入next().

编辑:您可能要hasNextInt()在尝试读取输入之前检查.