Question

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(). The getChoice() is called when the possible options are printed.

Edit I fixed it. You needed to remove the try because it closes the scanner automatically. And scan.next() in the while-loop.

Was it helpful?

Solution

You need to consume the input from the Scanner

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

OTHER TIPS

Short explanation is above, but here's a bit more on Scanners:

Think of the Scanner like this.

Say you're given a String, "Hello world, this is a 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.

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.

Avoid putting .next() calls in conditional statements and return statements. I'm not sure of the specifics, but it can often break your without giving errors.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top