import java.util.Scanner;
class newClass {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
while (s.hasNext()) {
System.out.println(s.next());
}
s.close();
}
}
This program does not return to prompt (I have been running it through the Terminal). Why is that? How can I correct it?
This program does not return to prompt (I have been running it through the Terminal). Why is that?
Because s.hasNext() will block until further input is available and will only return false if it encounters end of stream.
From the docs:
Returns true if this scanner has another token in its input. This method may block while waiting for input to scan.
On a unix system you can end the stream by typing Ctrl+D which correctly returns control to the prompt, (or terminate the whole program by typing Ctrl+C).
How can I correct it?
You can either
System.in.close() programatically from another thread.This is a reply to a comment above. Here, the application will quit when receiving "quit".
import java.util.Scanner;
class newClass {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
while (s.hasNext()) {
String temp = s.next();
if(temp.trim().equals("quit"))
System.exit(0);
System.out.println(s.next());
}
s.close();
}
}
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