Alan
Alan

Reputation: 153

Scanner nextInt() and hasNextInt() problems

I'm investigating why scan.nextInt() consumes the previous integer from the second iteration onwards. Can anyone make sense of what's going on and also explain what "The scanner does not advance past any input" means exactly?

Please ignore the infinite loop. It's only for testing purposes.

Example:
Enter new data: 0
0
data entered
Enter data again: 1
executed
Enter new data: 1 <- this value is automatically entered (taken from previous input)
data entered
Enter data again:

    while(true)
    {
        System.out.print("Enter new data: ");
        System.out.println(scan.nextInt());
        //scan.nextLine();    //must include but I'm not sure why 
        System.out.println("data entered");
        System.out.print("Enter data again: ");
        if(scan.hasNextInt())
        {
            System.out.println("executed");
            //scan.nextLine();    //must include this too but not sure why
        }
    }

Upvotes: 2

Views: 7149

Answers (1)

Viktor K.
Viktor K.

Reputation: 2740

The general pattern is this :

while(scan.hasNextInt())
{
    System.out.println(scan.nextInt());
}

First you make sure that there is next int and if there is next one you do something with it. You are doing it other way round. First you consume it, than you check whether there is another one, which is wrong.

Why should we call hasNextXXX before nextXXX ? Because nextXXX can throw NoSuchElementException if there isn't such next token. Look at this example :

String str = "hello world";
Scanner scan = new Scanner(str);

There is no integer in this string, which means that

System.out.println(scan.nextInt());

will throw NoSuchElementException. But if you use the while loop that I wrote you first check that there is an Integer in the input before you try doing anything with it. Therefore this is the standard pattern instead of handling unnecessary exceptions.

Upvotes: 7

Related Questions