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());
}
5
  • 2
    can you paste your code for try to help you? Commented Aug 1, 2013 at 10:29
  • Probably br.readLine() != null !!! Commented Aug 1, 2013 at 10:30
  • paste your code?what you tried so for Commented Aug 1, 2013 at 10:30
  • @AndriasMeisyal It's still not clear. What type of input you want and what should be the output? If you put 1 2 3 as input, you cannot convert it to an integer because there are spaces between 1 2 3 without modification. Commented Aug 1, 2013 at 10:46
  • Yes, you're right. But, Sorry, it's single input each line.. Commented Aug 1, 2013 at 10:49

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

3 Comments

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
What would happen if my file contains null as string ??? I am unable to read full file, can this be a reason ?
@astuter null is a java keyword. "null" is a string. See the difference ?
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.