我打印不同的選項,用戶輸入一個數字來選擇正確的選項。它第一次工作,但是當選擇了一個選項時,它會根據選定的選項打印不同的選項。當用戶試圖從第二個打印列表中選擇一個選項時,程序會陷入無限循環。無限循環使用Scanner.hasNextInt
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()中被卡住了。當打印可能的選項時調用getChoice()。
編輯 我固定它。您需要刪除該試卷,因爲它會自動關閉掃描器。 while循環中的scan.next()。
這導致 'NoSuchelementException' 第一個列表是相同的,但是當第二個列表打印時,這會導致錯誤。 – SBylemans
但每次打印新選項列表時都會啓動掃描儀。這並不重要。 – SBylemans
但是每個掃描器都使用相同的'System.in',所以第一次它關閉的後續'Scanner'實例不能從'InputStream'中讀取 – Reimeus