Below is a section of my Reverse Polish Calculator.
If an integer is entered, push it to the stack and, if = is pressed, peek the result. However, I want to a
Try this:
public static void main(String[] args) {
try {
byte[] b = new byte[1024];
for (int r; (r = System.in.read(b)) != -1;) {
String buffer = new String(b, 0, r);
System.out.println("read: " + buffer);
}
} catch (Exception e) {
e.printStackTrace();
}
}
In this case the loop will stop when you press CTRL+D that is because CTRL+D sends an EOF
signal to the System.in
InputStream
which is -1
. That is the case on *nix systems, for Windows system, the EOF
signal is sent using the CTRL+Z key combination
I assume you are talking about a console application?
On unix systems, pressing Ctrl+D closes the stdin for an application.
This will result in the input stream underneath Scanner
closing, which will cause mySc.hasNext()
to return false.
On windows, users need to press Ctrl+Z enter for the same effect.
If the input stream has not been closed, then mySc.hasNext()
will block until it can return true
.
So you need to wrap your program in a while(mySc.hasNext())
loop, e.g.
public static void main(String[] args) {
Scanner mySc = new Scanner(System.in);
while(mySc.hasNext()) {
//If input is an integer, push onto stack.
if (mySc.hasNextInt()) {
System.out.println(String.format("myStack.push(%s);", mySc.nextInt()));
}
//Else if the input is an operator or an undefined input.
else {
//Convert input into a string.
String input = mySc.nextLine();
System.out.println(String.format("input = %s", input));
//Read in the char at the start of the string to operator.
// char operator = input.charAt(0);
// if (operator == '=') {
// //Display result if the user has entered =.
// }
// **else if ("CTRL-D entered") {
// System.exit(0);
// }**
}
}
}
give this code a try. it actually worked for me
// press ctrl+Z(windows) and ctrl+D(mac, linux) for input termination
StringBuilder out = new StringBuilder();
String text = null;
Scanner scanner = new Scanner( System.in );
while( scanner.hasNextLine() )
{
text = new String( scanner.nextLine() );
out.append( text );
}
scanner.close();
System.out.println( out );
System.out.println( "program terminated" );