使用Scanner.hasNextInt的无限循环

SBy*_*ans 0 java java.util.scanner

我打印不同的选项,用户输入一个数字来选择正确的选项.它第一次工作,但是当选择一个选项时,它会根据所选选项打印不同的选项.当用户尝试从第二个打印列表中选择一个选项时,程序会陷入无限循环.

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

它在getIntegerInput()中陷入困境.在打印可能的选项时调用getChoice().

编辑 我修好了.您需要删除该尝试,因为它会自动关闭扫描仪.而while循环中的scan.next().

Rei*_*eus 5

你需要消耗来自的输入 Scanner

while (!scan.hasNextInt()) {
    scan.next(); // consume non-integer values
}
Run Code Online (Sandbox Code Playgroud)