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:

JavaScript

The current output:

JavaScript

The ideal output:

JavaScript

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
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement