为什么当这段代码运行时,如果您输入"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");
}发布于 2018-03-25 11:01:59
当提示输入时,按键盘上的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键两次,它将打印出来。你的集成开发环境可能会添加一个回车符\r和一个换行符\r,这就是为什么33在Intellij上适合你而不适合我。
发布于 2018-03-25 10:30:47
因为InputStream读取为byte,而不是char。
readInt将读取4个byte来构造int。但您的输入3只有1个byte (0x33)。添加行拆分器(\r\n)(0x0d0a),只有3个byte不能构造int。您可以再次尝试回车,它将打印。
但正确的方法是将char读作char的方式。您可以使用Reader或Scanner
input = new Scanner(System.in);
i = input.nextInt();https://stackoverflow.com/questions/49471829
复制相似问题