3

I have problems when testing my code. I think that the problem has to do with using a BufferedReader reading from an InputStreamReader. I used IntelliJ and give the following input:

Hello
World!

Why is my program not printing 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());
    }
}
Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
Jeni
  • 31
  • 2

3 Answers3

3

Your code stunk in the first loop.

To fix this, just modify your loop condition to be the next:

while (line != null && !line.isEmpty()) {
    lines.push(line);
    line = br.readLine();
}

Then your loop will exit when you just hit Enter.

Or you can add any other exit code. Such as while (line != null && !line.equals("exit")). So when you enter in the console your exit code(exit in the example above) your loop will stop and you will get your desired output.

ar4ers
  • 740
  • 5
  • 19
1

You're getting stuck in an infinite loop because the following condition never evaluates to false:

while (line != null) {
  lines.push(line);
  line = br.readLine();
}
Coop
  • 309
  • 1
  • 9
0

Your code has to know when you are done providing input. On Ubuntu I had to input:

Hello
World

Than I did hit Strg + D to signal EOS. Afterwards I got the output:

Hello
World
Harmlezz
  • 7,972
  • 27
  • 35