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:
JavaScript
x
//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:
JavaScript
What is your name?
<blank space for input>
<Empty Space where error message should be>
The ideal output:
JavaScript
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:
JavaScript
// 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