-1

I've looked at the documentation for the methods but I still can't quite understand how they work. Here are my questions: .hasNextInt() checks the next integer value and doesn't consume anything, yet in my code below the first time it appears it allows a user to enter a value; why is that? Afterwards I have to use .next() to clear the current value of the scanner object I'm using and will not be prompted for a new value if I remove this from the while loop.

As for .nextInt(), it's only on the first iteration in the code that it checks for the last integer value in the scanner object, but when I enter it again it allows me to enter in a new value. This all seems very inconsistent and I'm having a hard time understanding what's going on under the hood.

    int integer=0;
    Scanner scan = new Scanner(System.in);
    System.out.println("Please enter an integer");

    while(!scan.hasNextInt())
    {
        System.out.println("Wrong");
        scan.next();
    }

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

    int newNumber = scan.nextInt();
    System.out.println(newNumber);
Elmer
  • 75
  • 5
  • `Scanner` operates on an incoming text stream. It has to read ahead to determine whether there will be a `nextInt`, and that requires waiting for some input. `has` peeks at the incoming stream but doesn't consume it. – chrylis -cautiouslyoptimistic- Jun 01 '19 at 22:15
  • hasNextInt() returns true if the next token is a valid integer. So it blocks until it knows what the next token is: it can only return true or false once it knows what the next token is. If the next token is, for example, "23" it returns true becuase 23 is an integer. If the next token is, for example, "abc", it returns false because "abc is not a valid integer. Once you know that the next token is a valid integer, you can call nextInt() to read it and get its value. – JB Nizet Jun 01 '19 at 22:18
  • Once you know it is not a valid integer, you need to read the token (but not as an integer since it isn't one) to be able to test the susequent token. – JB Nizet Jun 01 '19 at 22:18

2 Answers2

0

You can consider Scanner as Iterator. Iterator has two methods hasNext() which returns is there is some data but doesn't make any changes, and next() which returns an Object.

The same with Scanner. all next*() return something from a buffer, but has*() methods only check a possibility to retrieve the particular object from the buffer.

dehasi
  • 2,014
  • 16
  • 23
  • I understand that but it still doesn't make sense to me why in only some cases .hasNextInt() and .nextInt() allow for user input – Elmer Jun 01 '19 at 22:25
-1

the nextInt function doesn't consume new line characters

therefore you need to run a Scanner.nextLine to consume the rest of the line,

It's already explained in more detail here

Scanner is skipping nextLine() after using next() or nextFoo()?

Jay Steel
  • 36
  • 3