What does System.in.read actually return?

半世苍凉 提交于 2019-11-26 07:47:24

问题


What does :

System.in.read()

return ? The documentation says :

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

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


回答1:


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

The stream of bytes that is produced when you enter 10Enter on 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).

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)

49
48
10



回答2:


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

49 is the Unicode point value for 1.

Try to print:

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

This will help you to understand it more.




回答3:


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

49 is the ASCII code for the character 1.



来源:https://stackoverflow.com/questions/15273449/what-does-system-in-read-actually-return

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!