繁体   English   中英

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

[英]Input stream reader- read method return wrong value

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

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

这是我的第一个问题所以请忽略这些愚蠢的错误,我试着尽可能地写出来。 谢谢..

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

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

字符'5'的Unicode值为53,这就是你所看到的。 (毕竟你的变量是一个int 。)如果你将num1转换为char ,你会看到'5'。

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM