gpt4 book ai didi

java - 为什么我会收到输入无效无限循环?

转载 作者:行者123 更新时间:2023-12-02 08:41:26 26 4
gpt4 key购买 nike

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

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!

最佳答案

来自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.

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

关于java - 为什么我会收到输入无效无限循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22416769/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com