gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:02:34 26 4
gpt4 key购买 nike

我正在尝试使用 DataInputStream 从用户那里获取输入。但这会显示一些垃圾整数值而不是给定值。

代码如下:

import java.io.*;
public class Sequence {
public static void main(String[] args) throws IOException {
DataInputStream dis = new DataInputStream(System.in);
String str="Enter your Age :";
System.out.print(str);
int i=dis.readInt();
System.out.println((int)i);
}
}

输出是

Enter your Age :12

825363722

为什么我得到这个垃圾值以及如何更正错误?

最佳答案

问题是 readInt并不像您预期​​的那样行事。它不是读取字符串并将字符串转换为数字;它将输入读取为 *bytes:

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))

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

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

  • 49 - '1'
  • 50 - '2'
  • 13 - 回车
  • 10 - 换行

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

如果您想要一个简单的方法来读取输入,请查看 Scanner 并查看它是否是您需要的。

关于java - 在 java 中读取 DataInputStream 中的整数用户输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17326969/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com