Skip to content
Advertisement

While loop is not working as expected. Everything seems to be correct. How do I fix this problem?

So I have this program:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
       
        Scanner scan = new Scanner(System.in);
        String name = "";
        while(name.isBlank()) {
            System.out.println("Enter your name: ");
            name = scan.next();     
        }
        System.out.println("Hello "+ name + "!");
    }
}

This program is supposed to prompt the user to enter their name. And it is supposed to keep prompting them until they actually enter their name meaning that if they keep the input field blank and press enter, they will get prompted again. However, this program does not do that. Even if I press ENTER without entering my name, the program just freezes and doesn’t prompt again. Please help :(.

Advertisement

Answer

I would like to supplement Dan’s answer. The key here is what the documentation for next() indicates.

This method may block while waiting for input to scan

The question is, what does this mean? It means the OP’s code works the way it is supposed to.

Enter your name: 
[ENTER pressed]
[ENTER pressed]
[ENTER pressed]
[ENTER pressed]
[ENTER pressed]
hector
Hello hector!

Because there was no input when ENTER was pressed, the call to next() method blocks waiting for input. Once input is entered, the scanner input is consumed and the proper output is produced. Because the method is blocking, no looping occurs; thus giving the appearance that the code is frozen when it is not.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement