-2

Here's the code:

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.print("Number: ");
            if (scanner.hasNextInt()) {
                System.out.println(scanner.nextInt());
                break;
            } else {
                System.out.println("Not an integer.");
            }
        }
        scanner.close();
    }

When the value is an integer everything works fine, the loop breaks out, however when the input is not an integer I keep seeing this infinitely flooding the terminal:

Number: Not an integer.
Number: Not an integer.
Number: Not an integer.
...
...
...
Zoltan King
  • 1,964
  • 4
  • 18
  • 38
  • 1
    That's because `hasNextInt()` just checks whether the next input is an integer or not but it doesn't consume the input (try a `Scanner.nextLine()` in your else-block). Your code checks the same input over and over again. – Thomas Oct 21 '19 at 12:05
  • Because it doesn't read anything when there is not an `int` to read. – Maurice Perry Oct 21 '19 at 12:05
  • 3
    Possible duplicate of [Java: Infinite loop using Scanner in.hasNextInt()](https://stackoverflow.com/questions/1794281/java-infinite-loop-using-scanner-in-hasnextint) – Ivar Oct 21 '19 at 12:06

5 Answers5

1

The reason this is happening when using Scanner.hasNextInt() in conjunction with Scanner.nextInt() is because the nextInt() method does not consume the ENTER key strike from the scanner buffer (when you enter a number) so this ENTER keeps getting played indefinitely. You need to clear this out of the Scanner buffer (so to speak) and to do that, you need to do this:

} else {
    System.out.println("Not an integer.");
    scanner.nextLine();  // Clear Scanner buffer.
}

Another reason why I just use Scanner.nextLine() ;).

OH...and don't close the Scanner object unless you are sure your application is finished with it otherwise you will not be able to use it again until you restart your application. It is auto-closed and Garbage Collected when the application closes anyways.

DevilsHnd - 退職した
  • 8,739
  • 2
  • 19
  • 22
0
        if (scanner.hasNextInt()) {
            System.out.println(scanner.nextInt());
            break;
        } 

Because scanner.hasNextInt() is looking for an Integer input and if the input is integer it prints its value and breaks (break statement) the while loop (i.e come out of the loop) else it keeps scanning for integer input.

Also you are using condition true in while loop which means loop will keep executing infinitely until we break it.

Gaurav Dhiman
  • 953
  • 6
  • 11
  • But when the condition fails and the loop starts again why doesn't .hasNextInt() looks for an input again and blocks until the value is provided? – Zoltan King Oct 21 '19 at 12:38
  • Because hasNextInt() returns true or false i.e it checks whether there is any input and if the input is of type Integer or not. If there is no input or input typen is not Integer it simply returns false and does not block or wait. But if you will directly call nextInt() method then it will block – Gaurav Dhiman Oct 21 '19 at 12:58
0

That's simply because:

  1. You are not taking out the non integer element (so it doesn't advance)
  2. There is no other logic to leave the loop (while(true) is not nice anyway) if there is no integer.
Christian Frommeyer
  • 1,390
  • 1
  • 12
  • 20
0

You have entered an infinite loop if your scanner object does not recognize an integer input. Since you are not having a "break" inside the else{} block, it would loop through infinite number of times and flood the terminal. Insert a "break;" after the print statement

-1

add break; after System.out inside else bracket , so you can break your loop once you encounter a non-integer input.

while(true)
{
    if(Something) // What Ever
    {
        break;
    }
}
System.out.println("Something Happened");

so if something happens you'll see Something Happened Once.

Edit: If you want it to repeat asking, change it like this:

public static void main(String[] args) {
    Scanner scanner;
    while (true) {
        scanner= new Scanner(System.in);
        System.out.print("Number: ");
        if (scanner.hasNextInt()) {
            System.out.println(scanner.nextInt());
            break;
        } else {
            System.out.println("Not an integer.");
        }
    }
    scanner.close();
}
  • If you put a `break` in both the `if` and the `else`, there is no reason to have a while-loop in the first place. – Ivar Oct 21 '19 at 12:30
  • Yes, I want the program to repeat asking the Number if there is not a number input. – Zoltan King Oct 21 '19 at 12:33
  • You are right , anyway it was about usage of break and explaining its concept, Cause question is about why is this code stuck in infinite loop. – Code Hunter Oct 21 '19 at 12:35
  • Well in that Case your question is irrelevant @ZoltanKing , You should define Scanner Outside the While and initialize it inside of it to achieve that purpose you want – Code Hunter Oct 21 '19 at 12:40
  • Have you checked the code? The scanner is defined outside the while. It's not about that. What I don't understand is why doesn't the condition in the IF block executes again when while loops for the second, third time and so on. – Zoltan King Oct 21 '19 at 12:51
  • Yes I've checked it @ZoltanKing , it works fine, pay attention to its difference with your code. I initiated scanner inside while , but defined it outside it , so in each loop it will re-initiate it and you get what you need – Code Hunter Oct 21 '19 at 12:58