Pichi Wuana Pichi Wuana - 1 month ago 9x
Java Question

Checking hasNextInt() in if and then receive an input

So a simple program would be:

import java.util.*;
public class practice {
static Scanner reader = new Scanner(System.in);
public static void main(String[] args) {


int numberEntered = reader.nextInt();



So I have a misunderstanding.
is supposed to check if the next input will be an int or not. I saw this program and I don't understand how the number can be inputed. Because already for getting an input the
needs to be true and the program hasn't got an input. So how will the program get inside the if statement?


The method Scanner#hasNextInt(), in your case, is a blocking method. This means, it is a method which waits and does only return if some conditions are met. It looks something like this:

public boolean hasNextInt() {
    boolean condition = false;
    while(!condition) {
    return stuff;

To be more precise, the blocking method is Scanner#hasNext(). It is described in its documentation. If the method blocks or not depends on the Scanners source. If it is, for example System.in, it will wait. If it is just a File, it will read the whole file until its end and then return, no blocking.

So, what happens? The hasNextInt in your if-condition waits for you to enter some input (until you send it by typing Enter). Then the Scanner saves the input inside a buffer. hasNextInt checks the internal buffer but does not delete stuff from the buffer.

Now comes nextInt which reads from the internal buffer and also deletes the stuff inside it. It advances past read input.

You can read it in detail inside the documentation mentioned above.

Things short: Scanner#hasNextInt() waits for input before it returns true or false.