Reading Integer user input in DataInputStream in java?

耗尽温柔 提交于 2019-12-01 01:51:54

问题


I am trying to get input from user using DataInputStream. But this displays some junk integer value instead of the given value

My code is:

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

And the output is

Enter your Age :12

825363722

Pls explain. Why am I getting this junk value and how to correct the error?


回答1:


The problem is that readInt does not behave as you might expect. It is not reading a string and convert the string to a number; it reads the input as *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.

In this case, if you are in Windows and input 12 then enter, the bytes are:

  • 49 - '1'
  • 50 - '2'
  • 13 - carriage return
  • 10 - line feed

Do the math, 49 * 2 ^ 24 + 50 * 2 ^ 16 + 13 * 2 ^ 8 + 10 and you get 825363722.

If you want a simple method to read input, checkout Scanner and see if it is what you need.




回答2:


In order to get the data from the DataInputStream you have to do the following -

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

The readInt() method returns the next four bytes of this input stream, interpreted as an int. According to the java docs

However you should have a look at Scanner.




回答3:


The better way to do this is use 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);
}


来源:https://stackoverflow.com/questions/17326969/reading-integer-user-input-in-datainputstream-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!