我打印不同的选项,用户输入一个数字来选择正确的选项。第一次它有效,但是当选择一个选项时,它会根据所选选项打印不同的选项。当用户尝试从第二个打印列表中选择一个选项时,程序陷入无限循环。
protected int getIntegerInput(Scanner scan) {
while (! scan.hasNextInt())
;
return scan.nextInt();
}
protected <T> int getChoice(String description, List<T> list) {
printPosibilities(description, list);
while (true) {
try (Scanner scan = new Scanner(System.in)) {
int choice = getIntegerInput(scan) - 1;
scan.close();
if (isValidChoice(choice, list)) {
if (choice == list.size()) {
System.out.println("Canceled.");
return CANCEL;
}
return choice;
} else
throw new IllegalArgumentException();
} catch (InputMismatchException | IllegalArgumentException e) {
printInvalidChoice();
}
}
}
它卡在 getIntegerInput() 的 while 中。当打印可能的选项时调用 getChoice()。
编辑 我修好了它。您需要删除该尝试,因为它会自动关闭扫描仪。以及 while 循环中的 scan.next() 。
最佳答案
您需要使用来自扫描仪
的输入
while (!scan.hasNextInt()) {
scan.next(); // consume non-integer values
}
关于java - 使用 Scanner.hasNextInt 无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23680500/