Koen
Koen

Reputation: 481

Scanner in.hasNextInt() never returns true

I have tried two methods. Neither works and I'm seriously wondering why.

display(text) simply is System.out.println(text)

public int getMove() {

    int move = -2;
    display("It's your turn, pick a row [0-6] or [-1] for a hint: ");
    Scanner in = new Scanner(System.in);
    do {
        if (in.hasNextInt()) {
            move = in.nextInt();
        }
        if (move == -1) {
            display("How much time can I use?");
            move = -3;
            do {
                if (in.hasNextInt()) {
                    move = in.nextInt();
                }
            } while (move == -3);
            in.close();
            return -1 * move;
        }
    } while (move < -1);
    in.close();
    return move;

}

This code does not take any input (e.g. when I enter 5 it doesn't exit the do-while loop).

when I change

        if (in.hasNextInt()) {
            move = in.nextInt();
        }

to:

            move = in.nextInt();

it throws a java.util.NoSuchElementException.

Why is this happening?

Upvotes: 0

Views: 104

Answers (1)

RandomHuman
RandomHuman

Reputation: 81

This will skip reading anything that is not an integer

 if (in.hasNextInt()) {
        move = in.nextInt();
    }    

so when you enter "abcd" it will forever stay in the buffer.

Add in.nextLine() at the end of loop to "skip" invalid input.

Upvotes: 1

Related Questions