Write a Java class called getName that prompts a user for their name and then displays "Hello, [name here]!" The flow should look like the following:
What is your name? Randy Savage
Hello, Randy Savage!

If the user does not enter anything but presses Enter anyways, you should re-prompt for the user’s name. This flow should look like the following (note that there should be a space after any ? or :):

What is your name?
Please enter your name:
Please enter your name: Randy Savage
Hello, Randy Savage!

Respuesta :

Answer:

Following are the program in Java language

import java.util.*; // import package

class getName      // class getname

{

   public static void main(String[] args)  // main function

   {

         String str; // variable declaration

       Scanner scr1 = new Scanner(System.in); // create the instance of scanner class

       System.out.println("What is your name?");

     do  

       {

           System.out.print("Please enter your name: ");

           str = scr1.nextLine(); // Read the string by user  

           

           if(str.length() > 0) // check the condition  

           {  

               break;  // break the loop

           }

       }while(true); // iterating the loop

       System.out.println("Hello, " +str); // display the string in the proper format  

   }

}

Output:

What is your name?

Please enter your name: Randy Savage

Hello, Randy Savage

Explanation :

Following are the explanation of the java program

  • Create an instance of scanner class i.e "scr1".
  • Print the message on screen What is your name? by using System.out.println() method.
  • iterating the do-while loop for input in the "str" variable. If the user enters nothing then again asked for the input.
  • if(str.length() > 0) condition is used to terminate the loop if user input the string.
  • Finally, print the string in proper format which is mention in the question.