Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

problem with BufferedReader  RSS feed

 
Emili Calonge
Ranch Hand
Posts: 84
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok, so I'm trying to do a simple program which has to first read an int, and then read a String. The code is as follows:

My problem is that it reads the int, but then I want the program to wait until I write the string in the console, but it doesn't wait. I just enter an int and it doesn't wait, it leaves my string empty.
If I insert another read line between it works, so I supose that the problem is that BufferedReader doesn't clear the buffer correctly or something like this. I don't know I have no idea about how it works, but the thing is that I don't want to put an extra readline. Please somebody knows what is happening and how can I solve it?? Thanks.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

First, note that read() doesn't read an int like "123" or "-37" -- it reads and returns a single character. The return type is int so that the value can be -1 to represent EOF -- an invalid value for a character.

Second, once it's read that one character, any remaining characters -- including newlines created by pressing "Enter" -- still remain to be read. All of them, up to the next newline, will be read by the next call to readLine().

Have a look at the new Scanner class in Java 5; also have a look at Sun's I/O tutorial.
 
Emili Calonge
Ranch Hand
Posts: 84
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yep, I know that read doesn't read "1" as an int of value 1, it returns it's asci coding, I know. What I didn't know is this you've explained as return being available to the new read instruction, I'll read this documentation you talk about. Thanks.
 
Emili Calonge
Ranch Hand
Posts: 84
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm so happy you told me about this new Scanner class, it's just what I was looking for, Thanks a lot.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!