读整数并得到答案+ 10

Zac*_*lin 0 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;
}
Run Code Online (Sandbox Code Playgroud)

示例I/O:

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

我:2 - O:12

我:3 - O:13

我:5 - O:15

我:10 - O:20

我:99 - O:109

我:100 - O:110

Pet*_*rey 6

将字符添加到整数时,它会执行整数运算.

所以

 x + '\n'
Run Code Online (Sandbox Code Playgroud)

是相同的

 x + 10
Run Code Online (Sandbox Code Playgroud)

因为(int) '\n'10

你的意图是什么

 x + "\n"
Run Code Online (Sandbox Code Playgroud)

这是字符串算术

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

 System.out.println(x);
Run Code Online (Sandbox Code Playgroud)