I want to receive input from the keyboard one character at a time. The input can include white space, be of any length, and doesn't require a special character to mark its end.
The problem is that if I use an InputStreamReader
, it doesn't know when the end of the stream is reached because there is no limited buffer size and no special character to let it know when the end of input is reached.
I thought I could get it to work when I discovered that InputStreamReader.read() == -1
means that the end of input has been reached. However, putting an if statement to check if InputStreamReader.read() == -1
doesn't work because it never reaches this case.
InputStreamReader userInput = new InputStreamReader(System.in);
boolean end = false;
while(! end) {
int c = userInput.read();
if(c == -1) {
end = true;
} else {
System.out.println(c);
}
}
With the above code, I'd expect that after the user enters their input into the console, it prints each character's ASCII code one by one and then terminates.
However, the program continues to run and receive input because the if-condition is never met.
How can I let the program know when the end of input is reached?
EDIT: I discovered that the requirements of my assignment allow me to use the EOF character to mark the end of input, however when I enter it into the console without first pressing Enter, the program terminates without reading any of the preceding input. I'm using IntelliJ as my IDE.