tags:

views:

86

answers:

3

Hi,

This time I have a very lame problem, which was working perfectly but now its not:

        BufferedReader br = new BufferedReader(new InputStreamReader(
                System.in));

        while (br.readLine() != null) {
            System.out.println(br.readLine());
        }

Input file:

1
2
3
4
5
6
7
8
9

In command line: $java myprogram < inputfile

The result of the above written code is:

    2
    4
    6
    8
null

But the expected output should be same as input file! :(

Where am I going wrong?!

+4  A: 

You are calling br.readLine() twice. It's calling it once in the while condition and once to actually print it out. That's why you are only printing every other line.

Edit: Your condition should be:

while(br.ready()){
     System.out.println(br.readLine());
}
Poindexter
Depending on the underlying streams and readers, this could exit prematurely. The `ready()` method only tests whether the reader is guaranteed not to block, not whether there is more input.
erickson
Now that was a pure java newbie question! :PThanks!
zengr
+7  A: 

You shouldn't call readLine() twice in each loop.

Each time you call it, it reads a new line. Print the result of each call:

while (true) {
  String line = br.readLine();
  if (line == null)
    break;
  System.out.println(line);
}
erickson
+2  A: 

You can modify your code like:

String str=null;
   while ((str=br.readLine())!= null) {
      System.out.println(str);
   }

Kushal Paudyal