java System.in.read 实际返回什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15273449/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 19:03:54  来源:igfitidea点击:

What does System.in.read actually return?

javajava-io

提问by saplingPro

What does :

有什么作用:

System.in.read()

return ? The documentationsays :

返回 ?该文件说:

Returns: the next byte of data, or -1 if the end of the stream is reached.

返回: 数据的下一个字节,如果到达流的末尾,则返回 -1。

But for example if I enter : 10I get back 49. Why is that ?

但例如,如果我输入:10我回来了49。这是为什么 ?

回答by Andreas Dolk

49is the ASCII value of the char 1. It is the value of the first byte.

49是 char 的 ASCII 值1。它是第一个字节的值。

The streamof bytes that is produced when you enter 10Enteron your console or terminal contains the three bytes {49,48,10}(on my Mac, may end with 10,12 or 12 instead of 10, depending on your System).

当您输入所产生的字节10Enter控制台或终端包含3个字节{49,48,10}(我的Mac上,可以用10,12或12,而不是10结束,取决于你的系统)。

So the output of the simple snippet

所以简单片段的输出

int b = System.in.read();
while (b != -1) {
    System.out.println(b);
    b = System.in.read();
}

after entering a 10 and hitting enter, is (on my machine)

输入 10 并按 Enter 后,是(在我的机器上)

49
48
10

回答by Maroun

System.in.read()reads just one byte.

System.in.read()只读取一个字节

49is the Unicodepoint value for 1.

49Unicode的为点值1

Try to print:

尝试打印:

System.out.println((char)49);

System.out.println((char)49);

This will help you to understand it more.

这将有助于您更深入地了解它。

回答by Fabien

When you enter 10, it is not read as an integer but as a String or, more precisely here, an array of bytes.

当您输入 时10,它不是作为整数读取,而是作为字符串读取,或者更准确地说,这里是字节数组。

49 is the ASCII code for the character 1.

49 是字符的 ASCII 码1