且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在java中的DataInputStream中读取整数用户输入?

更新时间:2023-12-04 18:07:40

问题是 readInt 不像你期望的那样表现。它不是读取字符串并将字符串转换为数字;它将输入读作* bytes


读取四个输入字节并返回一个int值。设a-d为读取的第一到第四个字节。返回的值是:

Reads four input bytes and returns an int value. Let a-d be the first through fourth bytes read. The value returned is:

(((a & 0xff) << 24) | ((b & 0xff) << 16) |  
((c & 0xff) << 8) | (d & 0xff))

此方法适用于读取由接口DataOutput的writeInt方法写入的字节。

This method is suitable for reading bytes written by the writeInt method of interface DataOutput.

在这种情况下,如果您在Windows中输入 12 然后输入,则字节为:

In this case, if you are in Windows and input 12 then enter, the bytes are:


  • 49 - '1'

  • 50 - '2'

  • 13 - 回车

  • 10 - 换行

  • 49 - '1'
  • 50 - '2'
  • 13 - carriage return
  • 10 - line feed

算一算,49 * 2 ^ 24 + 50 * 2 ^ 16 + 13 * 2 ^ 8 + 10,你得到825363722。

Do the math, 49 * 2 ^ 24 + 50 * 2 ^ 16 + 13 * 2 ^ 8 + 10 and you get 825363722.

如果你想要一个简单的方法来读取输入,请结帐扫描仪然后查看是否这就是你需要的。

If you want a simple method to read input, checkout Scanner and see if it is what you need.