输入流读取器 - 读取方法返回错误的值

时间:2013-03-21 11:33:30

标签: java inputstream bufferedreader

这听起来很容易或者是一个古老的愚蠢问题,但对我来说却完全不同。 我已经为半降金字塔模式编写了一个程序,就像这样。

1

1 2

1 2 3

1 2 3 4

1 2 3 4 5

我知道这很容易,诀窍是我不想使用ScannerInteger.parseInt()这样做。我正在尝试使用BufferedReaderInputStreamReader执行此操作。 所以当我执行以下代码的main方法时输入为5的num。当我打印它时,它读为53。我不知道为什么会这样。但是当我使用'Integer.parseInt(br.readLine())'方法时,它会给出准确的输出。当read方法应该读取int值时,应该如何发生。请清除它。

    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();
    }

这是我的第一个问题所以请忽略愚蠢的错误,我尽力写出来。 感谢..

3 个答案:

答案 0 :(得分:7)

  

当我打印它时,它读为53。

是的,它会的。因为您正在调用返回单个字符的read(),或者为-1来表示数据的结束。

字符'5'的Unicode值为53,这就是你所看到的。 (毕竟,您的变量是int。)如果您将num1投射到char,则会看到'5'。

如果要将整数的文本表示转换为整数值,通常会使用Integer.parseInt等代码。

答案 1 :(得分:1)

Bufferreader将使用以下内容读取您需要在int中转换它的unicode值:

的Integer.parseInt(NUM1)  要么 Character.getNumericValue(NUM1)

答案 2 :(得分:1)

53为'5'的ASCII,转换ASCII以打印出正确的字符串。

相关问题