简体   繁体   English

使用Scanner.hasNextInt的无限循环

[英]Infinite loop using Scanner.hasNextInt

I print different options and the user inputs a number to choose the right option. 我打印了不同的选项,用户输入了一个数字以选择正确的选项。 The first time it works, but when a option is chosen, it prints different options based on the selected option. 第一次运行,但是当选择一个选项时,它会根据所选选项打印不同的选项。 When the user tries to choose an option from the second printed list, the program gets stuck in an infinite loop. 当用户尝试从第二个打印列表中选择一个选项时,程序陷入无限循环。

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();
        }
    }
}

It gets stuck in the while in getIntegerInput(). 它卡在getIntegerInput()中。 The getChoice() is called when the possible options are printed. 当打印可能的选项时,将调用getChoice()。

Edit I fixed it. 编辑我修复它。 You needed to remove the try because it closes the scanner automatically. 您需要删除该尝试,因为它会自动关闭扫描仪。 And scan.next() in the while-loop. 然后在while循环中使用scan.next()。

You need to consume the input from the Scanner 您需要使用Scanner的输入

while (!scan.hasNextInt()) {
    scan.next(); // consume non-integer values
}

Short explanation is above, but here's a bit more on Scanners: 上面有简短的解释,但有关扫描器的更多信息:

Think of the Scanner like this. 想到这样的Scanner

Say you're given a String , "Hello world, this is a String!" 假设您收到一个String ,“世界,您好,这是一个字符串!”
Think of it to be broken up by each white space ' '. 认为它被每个空格''分解。

Every time .next() is called on the Scanner, it moves the buffer to the next white space. 每次在扫描仪上调用.next() ,它将缓冲区移至下一个空白空间。

So... for this example: 所以...对于这个例子:

Scanner.next()
// grabs Hello
// "Hello world, this is a String!"
//       ^ Buffer
Scanner.next()
// grabs world,
// "Hello world, this is a String!"
//              ^ Buffer`

In your case, since you're using a while() loop, you need to call .next() (or .nextInt() ) somewhere inside the loop. 在您的情况下,由于您正在使用while()循环,因此需要在循环内的某个位置调用.next() (或.nextInt() )。

Avoid putting .next() calls in conditional statements and return statements. 避免将.next()调用放在条件语句和return语句中。 I'm not sure of the specifics, but it can often break your without giving errors. 我不确定具体细节,但是它经常会破坏您的内容而不会出错。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM