整数扫描程序的 n 个数量之和

Sum of n-amount of Integers Scanner

提问人:Kirsten de Wit 提问时间:10/25/2019 最后编辑:GBouffardKirsten de Wit 更新时间:11/2/2019 访问量:609

问:

我必须使用扫描仪输入未知数量的数字。一旦用户输入 -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);

我无法获得正确的总和。有人可以帮忙吗?

爪哇岛

评论

3赞 Thomas 10/25/2019
从循环中删除那一秒。您基本上是从控制台读取 2 个整数,但忽略第一个整数。还要在检查之前向上移动以将 -1 包含在总和中(如果不应该发生这种情况,请不要这样做)。read = scanner.nextInt();sum += read;
0赞 THess 10/25/2019
您能举例说明您得到的总和而不是预期的结果吗?
0赞 Kirsten de Wit 10/25/2019
我会输入数字 14 11 19 9 -1。我的答案最终是20。

答:

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循环中,你使用两次赋值,这打破了你的逻辑。readscanner.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);

这在我的情况下有效。 关闭扫描仪也会删除警告。