java 中的读取函数

the read function in java

我有这个代码:

public class test {
    public static void main(String args[]) throws IOException {
        BufferedReader in = new BufferedReader(new 
InputStreamReader(System.in));
        char x =(char)in.read();
        char y =(char)in.read();
        char z =(char)in.read();
        System.out.print(x+y+z);
    }
}

和这个输入:

1
2

输出为:

109

为什么我会得到这个输出? 我不明白 read 函数是如何工作的。 我尝试使用跳过功能,但也没有得到正确答案。

您正在以字符形式读取您的输入。您输入的是三个字符(1、2 和换行符):

  • 1 ASCII 值为 49。
  • 2 ASCII 值为 50。
  • line feed,ASCII 值为 10。

然后将这三个字符按其 ASCII 值相加,总数为 109。

问题是您误解了调用 read() 时 return 角色的编辑方式。

The character read, as an integer in the range 0 to 65535 (0x00-0xffff), or -1 if the end of the stream has been reached

read 方法 return 是一个 int,因此它可以 return 字符的 Unicode 代码。对于简单的字母和数字,Unicode 与 ASCII 重叠,其中 1 是 49,2 是 50,换行符是 10。这些代码的总和是 109。

选项: