Skip to content
Advertisement

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?

Advertisement

Answer

The only thing that you need to change is your condition in the while statement. Please use sc.hasNextLine() insted of sc.hasNext(). Then you will get desired output. Here is the working soltion:

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

    while (sc.hasNextLine()) { // here is the difference in the code
        // 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.hasNextLine(); // here is the difference in the code
        } else {
            // Print name
            System.out.println("Hello " + name + "!");
            break;
        } // End of conditional
    } // End of while loop
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement