我编写了一个 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/