read() method of BufferedReader and InputStreamReader

Why do I get an exception when parsing the characters to integer using the read() method instead of readLine() of BufferedReader. I tried using this code below:

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int a= Integer.parseInt(br.read());

error was : cannot convert int to string.. very strange error

Jon Skeet
people
quotationmark

Reader.read() just returns a single character - but as an int, so you can tell if you've reached the end of the data.

Now there isn't any Integer.parseInt(int) method, which is why the calling is failing - there isn't even Integer.parseInt(char). You could convert to char and then call Character.getNumericValue(char)... or you could just use:

int digit = br.read() - '0';

... and then check that digit is in the range 0-9.

Alternatively you could create a string from the single character you've read and call Integer.parseInt, but that seems like overkill...

people

See more on this question at Stackoverflow