1

当我运行以下代码并在提示输入时键入 50 时:

    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);
}

}

我得到以下输出:

请输入进入平台的人数:50 输入的人数 --> 53

为什么我输入 50 时返回 53 ?谢谢。

4

4 回答 4

4

BufferedReader#read()single character方法从您的输入中读取 a 。

因此,当您50作为输入传递时,它只是读取5并将其转换为ASCII等效的,即将53其存储在int变量中。

我认为您需要BufferedReader#readLine()这里的方法,它读取一行文本。

try {
    nPeople = Integer.parseInt(keyboard.readLine());  
} catch (IOException e) {
    e.printStackTrace();
}

您需要Integer.parseInt将字符串表示形式转换为integer.

于 2012-11-19T12:11:53.607 回答
1

BufferedReader 键盘 = new BufferedReader(new InputStreamReader(System.in)); 尝试 { nPeople = keyboard.read(); } catch (IOException e) { e.printStackTrace(); }

上面的代码将只读取您输入的输入的第一个字符。

它正在显示该字符的 ASCII 值。

尝试使用

 npeople = Integer.parseInt(keyboard.readLine());
于 2012-11-19T12:15:09.700 回答
0

因为'5'等于53(ascii码)

有关更多详细信息,请参见thisthis

于 2012-11-19T12:09:20.217 回答
0

尝试做这样的事情:

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);
}
于 2012-11-19T12:16:03.220 回答