'Java program that asks for user's name and prints it - issue with error message

I have a program that asks for the user's name and prints it back out. It can do that part fine, but it currently has the issue of not printing the proper error message when the user leaves the prompt empty and presses "Enter".

The code:

  //Get User Input
  Scanner sc = new Scanner(System.in);
  System.out.println("What is your name?");

  while (sc.hasNext()) {
     //User Input Variable
     String name = sc.nextLine();
     if (name == null || name.trim().isEmpty()) {
        //Error for empty input, keep asking for valid input
        System.out.print("Please, what is your name?\n");
        sc.next();
     } else {
        //Print name
        System.out.println("Hello " + name + "!");
        break;
     }//End of conditional
  }//End of while loop

The current output:

What is your name?
<blank space for input>
<Empty Space where error message should be>

The ideal output:

What is your name?
<blank space>
Please, what is your name?

What's wrong?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source