提问人:Kirsten de Wit 提问时间:10/25/2019 最后编辑:GBouffardKirsten de Wit 更新时间:11/2/2019 访问量:609
整数扫描程序的 n 个数量之和
Sum of n-amount of Integers Scanner
问:
我必须使用扫描仪输入未知数量的数字。一旦用户输入 -1,程序需要打印所有输入数字的总和,然后结束程序。-1 需要包含在总和中。
Scanner scanner = new Scanner(System.in);
int sum = 0;
while (true) {
int read = scanner.nextInt();
if (read == -1) {
break;
}
read = scanner.nextInt();
sum += read;
}
System.out.println(sum);
我无法获得正确的总和。有人可以帮忙吗?
答:
0赞
SJN
10/25/2019
#1
以下程序也会在您的总和中添加 -1。你读了两遍。read = scanner.nextInt();
Scanner scanner = new Scanner(System.in);
int sum = 0;
while (true) {
int read = scanner.nextInt();
sum += read;
if (read == -1) {
break;
}
}
System.out.println(sum);
}
评论
0赞
THess
10/25/2019
@Thomas “-1 需要包含在总和中。”由 OP 提供
2赞
Thomas
10/25/2019
@THess是的,现在看到:)
1赞
arkantos
10/25/2019
#2
在你的while循环中,你使用两次赋值,这打破了你的逻辑。read
scanner.nexInt()
Scanner scanner = new Scanner(System.in);
int sum = 0;
while (true) {
int read = scanner.nextInt();
if (read == -1) {
sum += read; //have to include -1 to sum
break;
}
//read = scanner.nextInt(); you have to delete this line
sum += read;
}
System.out.println(sum);
}
1赞
Nishant Kumar
10/25/2019
#3
Scanner scanner = new Scanner(System.in);
int sum = 0;
int read = 0;
while (read != -1) {
read = scanner.nextInt();
sum += read;
}
scanner.close();
System.out.println(sum);
这在我的情况下有效。 关闭扫描仪也会删除警告。
评论
read = scanner.nextInt();
sum += read;