输入流读取器 - 读取方法返回错误的值 [英] 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
1 2 3 4 5
我知道这很容易,诀窍是我不想通过使用<$ c $来做到这一点c>扫描仪和 Integer.parseInt()
。我试图用 BufferedReader
和 InputStreamReader
来做到这一点。
所以当我执行以下代码的main方法时输入为5的num。当我打印它时,它读为53。我不知道为什么会这样。但是当我使用'Integer.parseInt(br.readLine())'方法时,它会给出准确的输出。当read方法应该读取int值时,它应该如何发生。请清除它。
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..
推荐答案
当我打印它时,它读为53。 / p>
It reads it as 53 when i prints it.
是的,它会。因为你正在调用 read()
,它返回一个字符,或-1表示数据结束。
Yes, it would. Because you're calling read()
which returns a single character, or -1 to indicate the end of data.
字符'5'的Unicode值为53,这就是你所看到的。 (毕竟,你的变量是 int
。)如果你将 num1
强制转换为 char
,你会看到'5'。
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.
当你想要转换整数的文本表示时进入整数值,通常会使用 Integer.parseInt
等代码。
When you want to convert the textual representation of an integer into an integer value, you would usually use code such as Integer.parseInt
.
这篇关于输入流读取器 - 读取方法返回错误的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!