2

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
        }
    }
Alan
  • 151
  • 1
  • 3
  • 11
  • Explain what happens when you run this code, and what you expect to see happen? "[it] consumes the previous integer from the second iteration onwards" isn't clear to me. – dcsohl Dec 26 '13 at 21:05
  • You don't seem to be calling `nextInt()` anywhere in your sample code, but it's in your question title; am I missing something? – TypeIA Dec 26 '13 at 21:06
  • It's on the 4th line, @DavidNorris - `System.out.println(scan.nextInt());` – dcsohl Dec 26 '13 at 21:07
  • Indeed I was missing something ;) Thanks. – TypeIA Dec 26 '13 at 21:12

1 Answers1

7

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.

Viktor K.
  • 2,480
  • 2
  • 17
  • 28
  • Can you also include an explanation for what it means for scanner to not advance pass any input – Alan Dec 26 '13 at 21:51
  • How do you construct your Scanner? I don't understand this question well. Could you Describe this scenarion in more detail? – Viktor K. Dec 26 '13 at 21:57
  • Look at http://docs.oracle.com/javase/6/docs/api/java/util/Scanner.html#hasNextInt(int) – Alan Dec 26 '13 at 22:42