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());
    }
}

      

+3


source to share


3 answers


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.

+3


source


You are stuck in an infinite loop because the following condition never evaluates to false:



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

      

+1


source


Your code needs to know when you're done providing input. On Ubuntu I had to type:

Hello
World

      

Than I hit Strg + Dto signal EOS. Subsequently, I got the output:

Hello
World

      

0


source







All Articles