简体   繁体   中英

Entering a integer value using DataInputStream

while using DataInputStream to enter any value, i have to press the enter key twice, if i enter any single digit number...and in the code snippet written below

public void print()
   {
       DataInputStream in = new DataInputStream(System.in);
       try
       {
           System.out.println("Enter a digit");
           int n=in.readInt();
           System.out.println(n);
        }
        .
        .
        .
        .

while printing the value of n it usually shows some unexpected value... using BufferedReader does not cause the same problem...

When the value entered is 233, it shows 842216202 as the output... What can the possible error in the code be... Need help with this...

DataInputStream reads binary data. When you enter [2, 3, 3, \\n] it's equal to [0x32, 0x33, 0x33, 0x0A] which is (in big endian), 0x3233330A which is 842216202 (decimal format).

Change to a Scanner , it reads text and have convinance methods to transform the characters to (for example) an integer, your example using a Scanner :

Scanner in = new Scanner(System.in);
try {
    System.out.println("Enter a digit");
    int n = in.nextInt();
    System.out.println(n);
} ...

According to the Javadocs for DataInputStream , the readInt() method will read exactly four bytes from the underlying input stream. If the number you enter is less than four bytes long (such as a single-digit number), the read will continue until it reads four bytes. That means it will include the newline character you enter when you press the "enter" key, whose Unicode encoded value will be interpreted as an integer. This is probably the source of your errors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM