【问题标题】:BufferedReader input gives unexpected resultBufferedReader 输入给出了意外的结果
【发布时间】:2012-11-07 08:33:42
【问题描述】:

当我运行以下代码并在提示输入时键入 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 ?谢谢。

【问题讨论】:

  • 什么是keyboard 以及read() 方法的具体作用是什么?

标签: java input io bufferedreader


【解决方案1】:

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

更多详情请参阅thisthis

【讨论】:

    【解决方案2】:

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

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

    我觉得你这里需要BufferedReader#readLine() 方法,它读取一行文本。

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

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

    【讨论】:

    • 工作谢谢。但是我发现使用扫描仪要容易得多。 Scanner vs BufferedReader 的任何输入?
    • @Jatt.. 好吧,如果您的唯一目的是读取输入并打印它,那么BufferedReader 是一个更好的选择。但是如果你想用读取输入做一些parsing,那么在这种情况下当然用Scanner
    • 我觉得很高兴。稍后我需要使用实际的 int 值,所以 Scanner 似乎是最好的方法。无论如何,至少我知道将来如何使用 BufferedReader :)
    • @Jatt .. 当然可以。你应该知道你所有的选择。了解更多才能成为更好的程序员总是好的。祝你好运,享受编码:)
    【解决方案3】:

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

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

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

    尝试使用

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

    【讨论】:

    • 您不能将字符串分配给 int。
    【解决方案4】:

    尝试做这样的事情:

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

    【讨论】:

    • 没有这样的Integer.parseInteger(...)方法
    猜你喜欢
    • 2013-12-20
    • 1970-01-01
    • 1970-01-01
    • 2017-06-15
    • 1970-01-01
    • 2014-04-19
    • 2012-01-23
    • 2017-11-05
    • 1970-01-01
    相关资源
    最近更新 更多