Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read until end of file (EOF) using BufferedReader in Java?

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());
}
like image 781
meisyal Avatar asked Aug 01 '13 10:08

meisyal


1 Answers

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

like image 142
a question Avatar answered Oct 08 '22 14:10

a question