I am trying to get input from user using DataInputStream
. But this displays some junk integer value instead of the given value.
Here is the code:
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
Why am I getting this junk value and how to correct the error?
The readInt() method of DataInputStream class in Java is used to read four input bytes and returns a integer value. This method reads the next four bytes from the input stream and interprets it into integer type and returns. Specified By: This method is specified by readInt() method of DataInput interface.
An inputStream is the base class to read bytes from a stream (network or file). It provides the ability to read bytes from the stream and detect the end of the stream. DataInputStream is a kind of InputStream to read data directly as primitive data types.
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:
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With