2

当初始选择无效时,为什么这会导致我陷入无限循环?

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

输出:

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!
4

3 回答 3

9

Javadoc

当扫描器抛出InputMismatchException时,扫描器不会传递导致异常的令牌,以便可以通过其他方法检索或跳过它。

所以"df"字符串仍在扫描仪中。您必须通过调用next()或其他方式以某种方式清除它。

于 2014-03-14T22:21:59.057 回答
4

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.
    }
}
于 2014-03-14T22:22:10.153 回答
1

您仅在 try 子句中中断 while 语句。当您的 while 循环进入 catch 时,它不会中断循环。

while (true) {
  System.out.print("Choice:\t");
  try {
    int choice = scanner.nextInt();
  } catch (InputMismatchException e) {
    System.out.println("Invalid Input!");
  }
  finally {
   break;
  }
}
于 2014-03-14T22:22:21.137 回答