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 asingle characterfrom your input.So when you pass
50as input, it just reads5and converts it toASCIIequivalent that is53to store it inintvariable.I think you need
BufferedReader#readLine()method here, which reads a line of text.You need
Integer.parseIntmethod to convert the string representation into aninteger.