PsyCode
PsyCode

Reputation: 664

Why doesn't Scanner seem to look for a new int every time nextInt is called

Why does it continue in the while loop repeating "Please enter a valid number" and it keeps repeating without stopping to let the user input something.

        while (true) { //This will continually run until something is returned, AkA the number 1 or 2
        Scanner s = new Scanner(System.in);
        try {
            input = s.nextInt();
        } catch (Exception e) {
            System.out.println("Please enter a valid number!");
        }
        s.close();
    }

When I use the debugger nothing seems to be the cause of this problem and no errors are thrown. What is causing this problem and how can it be fixed?

Upvotes: 1

Views: 70

Answers (2)

user562
user562

Reputation: 88

Remove

s.close();

And Define your Scanner object outside the while loop as it not an Issue. Btw, I've tried your code, it worked fine until I entered a input which is not an int. When I entered a string, the exception sysout statement keeps printing infinitely

So you've to add

string junk = s.nextLine();

in your Exception block like paxdiablo said so that it wont repeat continuously.

Upvotes: 0

paxdiablo
paxdiablo

Reputation: 881303

Closing a scanner also closes the underlying stream if it implements the Closable interface.

That's System.in in this case and, once closed, you won't be able to create a scanner using it again.

See http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#close() for the gritty detail.

But, even if you fix that problem, an exception from nextInt will not advance the stream pointer so, the next time you call it, it will find exactly the same data in the input stream again.

You need to clear out the erroneous data before trying again. Since you're accepting user input, one solution is to call nextLine and throw that away;

string junk = s.nextLine();

Upvotes: 1

Related Questions