BufferedReader输入会产生意外结果

时间:2012-11-19 12:07:57

标签: java input io bufferedreader

当我运行以下代码并在提示输入时输入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 个答案:

答案 0 :(得分:4)

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

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

我认为你需要BufferedReader#readLine()方法,它会读取一行文字。

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

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

答案 1 :(得分:1)

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

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

它显示该字符的ASCII值。

尝试使用

 npeople = Integer.parseInt(keyboard.readLine());

答案 2 :(得分:0)

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

有关详细信息,请参阅thisthis

答案 3 :(得分: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);
}