jshbrntt
jshbrntt

Reputation: 5405

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!

Upvotes: 2

Views: 354

Answers (3)

Aycan Yaşıt
Aycan Yaşıt

Reputation: 2124

You break while statement in only in try clause. When your while loop enters in catch, it just doesn't break the loop.

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

Upvotes: 1

kamituel
kamituel

Reputation: 35970

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.
    }
}

Upvotes: 4

durron597
durron597

Reputation: 32343

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.

Upvotes: 9

Related Questions