20

I have problem with reading the input until EOF in Java. In here, there are single input and the output consider the input each line.

Example:

input:

1
2
3
4
5

output:

0 
1
0
1
0

But, I have coded using Java, the single output will printed when I was entering two numbers. I want single input and print single output each line (terminate EOF) using BufferedReader in Java.

This is my code:

BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
StringBuffer pr = new StringBuffer("");

String str = "";
while((str=input.readLine())!=null && str.length()!=0) {
    BigInteger n = new BigInteger(input.readLine());
}
ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
meisyal
  • 811
  • 1
  • 11
  • 18

2 Answers2

29

You are consuming a line at, which is discarded

while((str=input.readLine())!=null && str.length()!=0)

and reading a bigint at

BigInteger n = new BigInteger(input.readLine());

so try getting the bigint from string which is read as

BigInteger n = new BigInteger(str);

   Constructor used: BigInteger(String val)

Aslo change while((str=input.readLine())!=null && str.length()!=0) to

while((str=input.readLine())!=null)

see related post string to bigint

readLine()
Returns:
    A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached 

see javadocs

Community
  • 1
  • 1
Shahrzad
  • 1,062
  • 8
  • 26
  • Oh, my God. Thanks, It works, I can learn more about the lines which you have told to me. Thanks and thanks again for you, @a question – meisyal Aug 01 '13 at 10:54
  • What would happen if my file contains `null` as string ??? I am unable to read full file, can this be a reason ? – Uniruddh Mar 31 '14 at 13:44
  • 1
    @astuter `null` is a java keyword. `"null"` is a string. See the difference ? – dimitris93 Jun 18 '15 at 22:06
7

With text files, maybe the EOF is -1 when using BufferReader.read(), char by char. I made a test with BufferReader.readLine()!=null and it worked properly.

alex
  • 79
  • 1
  • 2