Elmer
Elmer

Reputation: 75

Issue with some simple exception handling using .hasNextInt() in Java?

I'm creating an array list for a menu of food items which correspond to a number on a menu. Most of that is left out: my main issue is that the error message does not display for the first time the user does not enter an integer value. Nothing will show on the console after I press enter, but if I again enter something that isn't an integer it will work like it should and display the error message.

Edit: something else I should note is that earlier in the code I use the same scanner object so use .next() to clear it of the previous value it had.

        orderArray = new String[length];
        menuDisplay(); 
        int item; //the item number that user must enter
        for(int i=1; i<=length;i++)
        {
            System.out.println("Please choose item #"+ i+": ");
            scan.next();
            while(!scan.hasNextInt()) //this while loop checks that an integer value has been entered
            {
                System.out.println("Please enter an integer value from the above menu.");
                scan.next();
            }

        }

Upvotes: 1

Views: 49

Answers (1)

Andreas
Andreas

Reputation: 159165

The hasNextInt check the next token, not the token just received, so always call hasNextXxx() before calling nextXxx().

You'd also want to actually get the integer value and assign it to item.

Rearrange your code like this:

System.out.println("Please choose item #"+ i+": ");
while (!scan.hasNextInt()) //this while loop checks that an integer value has been entered
{
    System.out.println("Please enter an integer value from the above menu.");
    scan.next(); // skip bad token
}
item = scan.nextInt();

Upvotes: 1

Related Questions