在Java中读取DataInputStream中的Integer用户输入?

问题描述 投票:9回答:4

我正在尝试使用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

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

java datainputstream
4个回答
21
投票

问题是readInt的行为不符合您的预期。它不是在读取字符串并将字符串转换为数字。它将输入读取为* bytes

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

readInt

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

在这种情况下,如果您在Windows中并输入(((a & 0xff) << 24) | ((b & 0xff) << 16) | ((c & 0xff) << 8) | (d & 0xff)) ,然后输入,则字节为:

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

进行数学运算,49 * 2 ^ 24 + 50 * 2 ^ 16 + 13 * 2 ^ 8 + 10,得到825363722。

如果您想使用一种简单的方法来读取输入,请签出12,看看是否需要它。


1
投票

为了从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(); 方法返回此输入流的后四个字节,将其解释为int。根据readInt()

但是您应该看看java docs


0
投票

更好的方法是使用Scanner

Scanner

0
投票
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter your Age :\n");
    int i=sc.nextInt();
    System.out.println(i);
© www.soinside.com 2019 - 2024. All rights reserved.