Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Input stream reader- read method return wrong value

This may sound very easy or an old stupid question, but it is quite different for me. I have written a Program for a half-Descending pyramid Pattern which is like this.

1

1 2

1 2 3

1 2 3 4

1 2 3 4 5

I know this is very easy, the trick is I don't wanna do this by use of Scanner and Integer.parseInt(). I am trying to do this with BufferedReader and InputStreamReader. So when I execute the following code of my main method with a input of 5 in num. It reads it as 53 when I print it. I have no idea why it's happening. But when I use the 'Integer.parseInt(br.readLine())' method it gives the exact output. How is it supposed to happen when read method is supposed to read int values. Please clear it.

    int num1;   
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Enter hte value of num1");
    //num1=Integer.parseInt(br.readLine());
    num1=br.read();
    System.out.println(num1);
    for(int i=0;i<num1;i++)
    {
        for(int j=0;j<=i;j++)
        {
            System.out.print(j+"\t");

        }
        System.out.println();
    }

It's my first question so please ignore the silly mistakes, I have tried to write it as best as I could. Thanks..

like image 835
AJ027 Avatar asked Jan 14 '23 21:01

AJ027


2 Answers

It reads it as 53 when i prints it.

Yes, it would. Because you're calling read() which returns a single character, or -1 to indicate the end of data.

The character '5' has Unicode value 53, so that's what you're seeing. (Your variable is an int, after all.) If you cast num1 to a char, you'll see '5' instead.

When you want to convert the textual representation of an integer into an integer value, you would usually use code such as Integer.parseInt.

like image 107
Jon Skeet Avatar answered Jan 17 '23 15:01

Jon Skeet


Bufferreader will read unicode value you need to convert it in a int by using:

Integer.parseInt(num1) or Character.getNumericValue(num1)

like image 36
commit Avatar answered Jan 17 '23 16:01

commit