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.
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
.