Reputation: 3381
When I run the following code and type 50 when prompted for input:
private static int nPeople;
public static void main(String[] args) {
nPeople = 0;
System.out.println("Please enter the amount of people that will go onto the platform : ");
BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
try {
nPeople = keyboard.read();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(" The number of people entered --> " + nPeople);
}
}
I get the following output:
Please enter the amount of people that will go onto the platform : 50 The number of people entered --> 53
Why is it returning 53 when I typed 50 ? Thanks.
Upvotes: 1
Views: 385
Reputation: 10747
Try doing something like this :
private static int nPeople;
public static void main(String[] args) {
nPeople = 0;
System.out.println("Please enter the amount of people that will go onto the platform : ");
BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
try {
String input = reader.readLine();
nPeople = Integer.parseInt(input);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(" The number of people entered --> " + nPeople);
}
Upvotes: 0
Reputation: 1852
BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in)); try { nPeople = keyboard.read(); } catch (IOException e) { e.printStackTrace(); }
The above code will read only the first character of your entered input.
And it was displaying the ASCII value of that character.
try using
npeople = Integer.parseInt(keyboard.readLine());
Upvotes: 1
Reputation: 213243
BufferedReader#read()
method reads a single character
from your input.
So when you pass 50
as input, it just reads 5
and converts it to ASCII
equivalent that is 53
to store it in int
variable.
I think you need BufferedReader#readLine()
method here, which reads a line of text.
try {
nPeople = Integer.parseInt(keyboard.readLine());
} catch (IOException e) {
e.printStackTrace();
}
You need Integer.parseInt
method to convert the string representation into an integer
.
Upvotes: 4