try/catch with InputMismatchException creates infinite loop

前端 未结 7 900
醉话见心
醉话见心 2020-11-22 13:27

So I\'m building a program which takes ints from user input. I have what seems to be a very straightforward try/catch block which, if the user doesn\'t enter an int, should

相关标签:
7条回答
  • 2020-11-22 14:09

    You need to call next(); when you get the error. Also it is advisable to use hasNextInt()

           catch (Exception e) {
                System.out.println("Error!");
               input.next();// Move to next other wise exception
            }
    

    Before reading integer value you need to make sure scanner has one. And you will not need exception handling like that.

        Scanner scanner = new Scanner(System.in);
        int n1 = 0, n2 = 0;
        boolean bError = true;
        while (bError) {
            if (scanner.hasNextInt())
                n1 = scanner.nextInt();
            else {
                scanner.next();
                continue;
            }
            if (scanner.hasNextInt())
                n2 = scanner.nextInt();
            else {
                scanner.next();
                continue;
            }
            bError = false;
        }
        System.out.println(n1);
        System.out.println(n2);
    

    Javadoc of Scanner

    When a scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method.

    0 讨论(0)
提交回复
热议问题