在java中的DataInputStream中读取整数用户输入?
我试图从用户使用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); } }
输出是
输入您的年龄:12
825363722
请解释一下。 为什么我得到这个垃圾值以及如何纠正错误?
问题是readInt
行为与您的预期不同。 它不是读取字符串并将字符串转换为数字; 它将输入读作* 字节 :
读取四个输入字节并返回一个int值。 设ad为读取的第一个到第四个字节。 返回的值是:
(((a & 0xff) << 24) | ((b & 0xff) << 16) | ((c & 0xff) << 8) | (d & 0xff))
此方法适用于读取由接口DataOutput的writeInt方法写入的字节。
在这种情况下,如果您在Windows中输入12
然后输入,则字节为:
- 49 - '1'
- 50 - '2'
- 13 - 回车
- 10 - 换行
做数学,49 * 2 ^ 24 + 50 * 2 ^ 16 + 13 * 2 ^ 8 + 10,你得到825363722。
如果您想要一种简单的方法来读取输入,请检查Scanner
并查看它是否是您需要的。
为了从DataInputStream
获取数据,您必须执行以下操作 –
DataInputStream dis = new DataInputStream(System.in); StringBuffer inputLine = new StringBuffer(); String tmp; while ((tmp = dis.readLine()) != null) { inputLine.append(tmp); System.out.println(tmp); } dis.close();
readInt()
方法返回此输入流的后四个字节,解释为int。 根据java文档
但是你应该看一下Scanner 。
更好的方法是使用Scanner
Scanner sc = new Scanner(System.in); System.out.println("Enter your Age :\n"); int i=sc.nextInt(); System.out.println(i);
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=Integer.parseInt(dis.readLine()); System.out.println((int)i); }