The problem is that the program (like yours) does not know that the user has completed data entry, unless the user ... somehow ... does not say so.
The user can do this in two ways:
Enter the “end of file” marker. On UNIX and Mac OS, this is (usually) CTRL + D and on Windows CTRL + Z. This will cause hasNextLine() false .
Enter some special input that the program recognizes as meaning "I am done." For example, it can be an empty string or some special value, for example, "exit". The program must verify this specifically.
(You can also use a timer and assume that the user has completed work if he does not enter the input within N seconds or N minutes. But this is not a user-friendly way to do this.)
The reason your current version crashes is because you use == to check for an empty string. You should use equals or isEmpty methods. (See How do I compare strings in Java? )
Other things to consider are case sensitivity (for example, “exit” versus “exit”) and the effect of leading or trailing spaces (for example, “exit” versus “exit”).
Stephen c
source share