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?
In order to get the data from the
DataInputStream
you have to do the following -The
readInt()
method returns the next four bytes of this input stream, interpreted as an int. According to the java docsHowever you should have a look at Scanner.
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: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.The better way to do this is use
Scanner