public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
try {
while (scan.hasNextLine()){
String line = scan.nextLine().toLowerCase();
System.out.println(line);
}
} finally {
scan.close();
}
}
Just wondering how I can terminate the program after I have completed entering the inputs? As the scanner would still continue after several "Enter" assuming I am going to continue entering inputs... I tried:
if (scan.nextLine() == null) System.exit(0);
and
if (scan.nextLine() == "") System.exit(0);
They did not work.... The program continues and messes with the original intention,
Even though a scanner is not a stream, you need to close it to indicate that you're done with its underlying stream [1]. IDEs like Eclipse will often issue a warning that you have a "Resource leak: 'scanner' is never closed". Note: don't close a Scanner that's tied to System.in!
You can cancel active requests for input either by interrupting the thread, or by calling cancel(), which canceles the currently waiting request. It uses Semaphores and threads to create a blocking nextLine() method that can be interrupted/canceled elsewhere.
Java Clear Scanner Using nextLine() To clear the Scanner and to use it again without destroying it, we can use the nextLine() method of the Scanner class, which scans the current line and then sets the Scanner to the next line to perform any other operations on the new line.
It is recommended to always close the Scanner when we are reading a file. It ensures that no input or output stream is opened, which is not in use. The following example shows how we can read a string from the file and then close the scanner once the operation has been done.
The problem is that a program (like yours) does not know that the user has completed entering inputs unless the user ... somehow ... tells it so.
There are two ways that the user could do this:
Enter an "end of file" marker. On UNIX and Mac OS that is (typically) CTRL+D, and on Windows CTRL+Z. That will result in hasNextLine()
returning false
.
Enter some special input that is recognized by the program as meaning "I'm done". For instance, it could be an empty line, or some special value like "exit". The program needs to test for this specifically.
(You could also conceivably use a timer, and assume that the user has finished if they don't enter any input for N seconds, or N minutes. But that is not a user-friendly way, and in many cases it would be dangerous.)
The reason your current version is failing is that you are using ==
to test for an empty String. You should use either the equals
or isEmpty
methods. (See How do I compare strings in Java?)
Other things to consider are case sensitivity (e.g. "exit" versus "Exit") and the effects of leading or trailing whitespace (e.g. " exit" versus "exit").
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With