Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java-Convert String to int when using BufferedReader

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

like image 368
aqua Avatar asked May 22 '13 09:05

aqua


People also ask

Can BufferedReader read String?

2.3. BufferedReader is synchronized (thread-safe) while Scanner is not. Scanner can parse primitive types and strings using regular expressions.

How do I get input from BufferedReader?

BufferedReader input = new BufferedReader (new InputStreamReader (System.in)); Once we have created a BufferedReader we can use its method readLine() to read one line of characters at a time from the keyboard and store it as a String object. String inputString = input. readLine();

Is BufferedReader more efficient than FileReader?

BufferedReader is much more efficient than FileReader in terms of performance. FileReader directly reads the data from the character stream that originates from a file.


2 Answers

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());
like image 66
Kevin Bowersox Avatar answered Sep 22 '22 06:09

Kevin Bowersox


When using BufferedReader you have to take care of the exceptions it may throw. Also, the Integer.parseInt(String s) method may throw an NumberFormatException if the String you're providing cannot be converted to Integer.

try {
   BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
   while ((thisLine = br.readLine()) != null) {
     System.out.println(thisLine);
     Integer parsed = Integer.parseInt(thisLine);
     System.out.println("Parsed integer = " + parsed);
   } 
 } catch (IOException e) {
    System.err.println("Error: " + e);
 } catch (NumberFormatException e) {
    System.err.println("Invalid number");
 }
like image 34
Konstantin Yovkov Avatar answered Sep 24 '22 06:09

Konstantin Yovkov