Testing Reading a Buffered Reader from an Input Stream
I'm having problems testing my code. I think the problem is with the use of reading BufferedReader from InputStreamReader. I used IntelliJ and gave the following input:
Hello
World!
Why doesn't my program print anything? Here is my code:
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Deque<String> lines = new ArrayDeque<>();
String line = br.readLine();
while (line != null) {
lines.push(line);
line = br.readLine();
}
while (!lines.isEmpty()) {
System.out.println(lines.pop());
}
}
source to share
Your code is placed in the first loop.
To fix this, simply change the loop condition as follows:
while (line != null && !line.isEmpty()) {
lines.push(line);
line = br.readLine();
}
Then your loop will exit when you just click Enter.
Or you can add any other exit code
. Eg while (line != null && !line.equals("exit"))
. So when you type yours into the console exit code
( exit
in the example above), your loop will stop and you will get the desired output.
source to share