Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (9.5k points)

Below is my code to get input from a user using 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);

    }

}

Here’s the output: 

Enter your Age:12

825363722

Can anyone tell me why I’m getting a garbage value and how to correct this error?

1 Answer

0 votes
by (19.7k points)

readInt does not read the string and convert the string to a number; it reads the input as *bytes. 

Below code reads  four input bytes and returns an int value: 

(((a & 0xff) << 24) | ((b & 0xff) << 16) |  

((c & 0xff) << 8) | (d & 0xff))

Use readInt to read bytes which are written by the writeInt method of interface DataOutput.


 

In you case when you read input 12 on Windows what happens is: 

49 - '1'

50 - '2'

13 - carriage return

10 - line feed

As you run this, it does 49 * 2 ^ 24 + 50 * 2 ^ 16 + 13 * 2 ^ 8 + 10 and the output you get is  825363722. Better go for a simple Scanner to read input.

Interested in Java? Check out this Java tutorial by Intellipaat. 

Related questions

0 votes
1 answer
0 votes
1 answer
asked Mar 9, 2021 in Java by dante07 (13.1k points)
0 votes
1 answer
asked Feb 16, 2021 in Java by Jake (7k points)
0 votes
0 answers
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...