Java-Convert String to int when using BufferedReader

aqua picture aqua · May 22, 2013 · Viewed 71.1k times · Source

How do you convert a String to int when using BufferedReader? as far as i remember,its something like below:

System.out.println("input a number");

int n=Integer.parseInt(br.readLine(System.in));

but for some reason,its not working.

the error message says:

no suitable method found for readLine(java.io.InputStream)

it also says br.readLine is not applicable

Answer

Kevin Bowersox picture Kevin Bowersox · May 22, 2013

An InputStreamReader needs to be specified in the constructor for the BufferedReader. The InputStreamReader turns the byte streams to character streams. As others have mentioned be cognizant of the exceptions that can be thrown from this piece of code such as an IOException and a NumberFormatException.

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("input a number");
int n = Integer.parseInt(br.readLine());