java - 读取整数并得到答案 + 10

标签 java input stream

我编写了一个 readInt() 方法来从 System.in 读取整数,但由于某种原因,返回的每个整数都相差 10。无论数字是一位还是几位,这都让我感到困惑。我的代码如下,我哪里出错了?

/**
 * @return The next integer read from the Input Stream
 */
public static int readInt() throws IOException {
    BufferedInputStream in = new BufferedInputStream(System.in);
    char c = (char) in.read();
    int num = 0, cNum = Character.getNumericValue(c);

    //Checks that the current value of c is in fact a single digit number (as it must be to be a char and an int)
    while (cNum > -1 && cNum < 10) {
        num = num * 10 + cNum;

        c = (char) in.read();
        cNum = Character.getNumericValue(c);
    }

    //If no number has been read, keep reading until one is read
    if (num == 0 && c != '0') {
        return readInt();
    }

    System.out.print(num + '\n');
    return num;
}

示例 I/O:

输入(I):1 - 输出(O):11

我:2 - 奥:12

我:3 - 奥:13

我:5 - 奥:15

我:10 - 奥:20

我:99 - 奥:109

我:100 - 奥:110

最佳答案

当你将一个字符添加到一个整数时,它会进行整数运算。

所以

 x + '\n'

相同
 x + 10

因为 (int) '\n'10

你想要的是

 x + "\n"

它进行字符串算术

但是更简单/更有效的解决方案是

 System.out.println(x);

关于java - 读取整数并得到答案 + 10,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20600840/

相关文章:

c - 在 C 中读取字符串以防止出现问题的正确方法是什么

c# - 该流不支持seek操作,使用stream

java - 是否可以通过 JBoss EL 解析器在 EL 中使用对象作为函数参数?

java - struts2 和 jaxb(适用于高于 2.0.x 的 struts2 版本)

delphi - 无法获取元素...网络浏览器的元素。 'A' 和 'INPUT' 等等...delphi 2007

java - 两次读取输入流而不将其存储在内存中

ruby-on-rails - 将流写入回形针

java - 从 URL 中提取 Android 应用 ID

java - 获取枚举类型变量的注释

python - 如何在Python中获取输入的特定部分以及多段落输入