我试图从键盘输入中找出最多四个数字。
我用过bufferedReader
由于某种原因,输入的数值会相加而不是产生最大值。
我尝试使用 Scanner
类并且它按预期工作。
BufferedReader in = new BufferedReader(new
InputStreamReader(System.in));
int a = in.read();
int b = in.read();
int c = in.read();
int d = in.read();
int n, m;
if (a > b) {
n = a;
}
else {
n = b;
}
if (c > d) {
m = c;
}
else {
m = d;
}
int max = n > m ? n : m;
System.out.println(max);
输出是所有这些输入值的总和,但我只期望其中的最大值。
最佳答案
尝试运行您的代码,如果我输出值,我会看到我输入的字符的数值。
public class Test {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new
InputStreamReader(System.in));
int a = in.read();
int b = in.read();
int c = in.read();
int d = in.read();
System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(d);
in.close();
}
如果我在得到每个数字后按 Enter
1
2
49
10
50
10
3
Process finished with exit code 0
在 1 和 2 之后,我按下了 Enter 按钮 - 所以读者读到 1 enter 2 enter 并且输出是 49(“1”的数值),然后是 10 (我的操作系统 Windows 10 中新行符号的数值),50(“2”的数值)。所以,事实上,这些数字并没有相加。
这就是您所需要的(至少是选项之一)
int a = Integer.valueOf(in.readLine());
int b = Integer.valueOf(in.readLine());
int c = Integer.valueOf(in.readLine());
int d = Integer.valueOf(in.readLine());
关于java - 为什么使用 BufferedReader 将数字输入值相加?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57327759/