Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!
like image 759
Joshua Barnett Avatar asked Dec 02 '25 08:12

Joshua Barnett


2 Answers

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.

like image 98
durron597 Avatar answered Dec 04 '25 23:12

durron597


Scanner is trying to parse and return the same token over and over again (and it's not integer, so it's throwing an exception). You could fix it by discarding invalid token:

while (true) {
    System.out.print("Choice:\t");
    try {
        int choice = scanner.nextInt();
        break;
    } catch (InputMismatchException e) {
        System.out.println("Invalid Input!");
        scanner.next();                         // here, discard invalid token.
    }
}
like image 36
kamituel Avatar answered Dec 05 '25 00:12

kamituel