Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
192 views
in Technique[技术] by (71.8m points)

java - 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+"");

        }
        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..

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...