运行这段代码后,如果您将“ 3”作为输入,却没有将“ Print”写入控制台,而将“ 33”写入了“ Print”,那怎么会这样呢?
public static void main(String[] args) throws Exception
{
DataInputStream input;
int any;
input = new DataInputStream(System.in);
any = input.readInt();
System.out.println("Print");
}
最佳答案
当提示您输入时,按键盘上的Enter
会添加换行符\n
。因此,键入333
并按Enter
将产生以下值存储在any
中:858993418
。
查看DataInputStream#readInt
的源代码,我们看到以下内容:
public final int readInt() throws IOException {
int ch1 = in.read();
int ch2 = in.read();
int ch3 = in.read();
int ch4 = in.read();
if ((ch1 | ch2 | ch3 | ch4) < 0)
throw new EOFException();
return ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + (ch4 << 0));
}
因此,我们可以使用以下公式计算
any
:('3' << 24) + ('3' << 16) + ('3' << 8) + '\n'
我不确定为什么您说
33
有效,因为仅输入33
并按Enter
不会为DataInputStream
提供四个字节,因此它会继续等待另一个字节。您可以按两次Enter
,它将打印。您的IDE可能会添加回车符\r
和换行符\r
,因此为什么33
在Intellij上对您有用而不对我有用。