Search code examples
javaexceptionjava.util.scannerinfinite-loopinputmismatchexception

Why am I getting an input Invalid Infinite Loop?


Why does this cause me to get stuck in an endless loop when the initial choice is invalid?

while (true) {
    System.out.print("Choice:\t");
    try {
        int choice = scanner.nextInt();
        break;
    } catch (InputMismatchException e) {
        System.out.println("Invalid Input!");
    }
}

Output:

Choice: df
Invalid Input!
Choice: Invalid Input!
Choice: Invalid Input!
Choice: Invalid Input!
Choice: Invalid Input!
Choice: Invalid Input!
Choice: Invalid Input!
Choice: Invalid Input!
Choice: Invalid Input!
Choice: Invalid Input!
Choice: Invalid Input!
Choice: Invalid Input!
Choice: Invalid Input!
Choice: Invalid Input!
Choice: Invalid Input!
Choice: Invalid Input!
Choice: Invalid Input!
Choice: Invalid Input!
Choice: Invalid Input!
Choice: Invalid Input!
Choice: Invalid Input!
Choice: Invalid Input!
Choice: Invalid Input!
Choice: Invalid Input!

Solution

  • From the Javadoc:

    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.

    So the "df" string is still in the Scanner. You have to clear it somehow, by calling next() or some other means.