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?

2 Answers

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. 

0 votes
ago by (2.6k points)

This becomes a problem when one calls DataInputStream.readInt() to read an integer directly from the input stream, not as a string representation of a number. And it obviously does not take a 12 as 12 but it takes it as ASCII of the characters that form the entire number 12.

Solution:

Use a BufferedReader or Scanner to correctly parse the input as a string and then convert it to an integer:

import java.io.*;

public class Sequence {

    public static void main(String[] args) throws IOException {

        BufferedReader br = new BufferedReader(newInputStreamReader(System.in));

        System.out.print("Enter your Age: ");

        int i = Integer.parseInt(br.readLine());

        System.out.println(i);

    }

}

 Using Scanner:

import java.util.Scanner;

public class Sequence {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        System.out.print("Enter your Age: ");

        int i = sc.nextInt();

        System.out.println(i);

        sc.close();

    }

}

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.9k answers

507 comments

693 users

...