【问题标题】:Reading Integer user input in DataInputStream in java?在java中的DataInputStream中读取整数用户输入?
【发布时间】:2013-06-23 23:59:10
【问题描述】:

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


    【解决方案1】:

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

    读取四个输入字节并返回一个 int 值。让 a-d 成为读取的第一个到第四个字节。返回值为:

    (((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 并查看它是否是您需要的。

    【讨论】:

      【解决方案2】:

      为了从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 docs

      不过,您应该看看 Scanner

      【讨论】:

        【解决方案3】:

        更好的方法是使用Scanner

            Scanner sc = new Scanner(System.in);
            System.out.println("Enter your Age :\n");
            int i=sc.nextInt();
            System.out.println(i);
        

        【讨论】:

          【解决方案4】:
          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);
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2020-07-27
            • 2014-08-18
            • 1970-01-01
            • 2012-01-29
            • 2015-08-02
            • 2017-10-07
            相关资源
            最近更新 更多