Reputation: 739
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
Upvotes: 8
Views: 76820
Reputation: 1
DataInputStream br=new DataInputStream(System.in);
System.out.println("input a number");
int n=Integer.parseInt(br.readLine(System.in));
Upvotes: -1
Reputation: 94459
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());
Upvotes: 19
Reputation: 32680
Try this:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("input a number");
try{
int n = Integer.parseInt(br.readLine());
} catch (IOException e) {e.printStackTrace();}
Upvotes: 0
Reputation: 4746
try this way
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String input = reader.readLine();
int n=Integer.parseInt(input);
Upvotes: 1
Reputation: 5366
try this
BufferedReader br = new BufferedReader(System.in);
String a=br.readLine()
Integer x = Integer.valueOf(a);
System.out.println(x);//integer value
Upvotes: 1
Reputation: 62864
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");
}
Upvotes: 1