首页 > 解决方案 > n 个整数扫描器的总和

问题描述

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

我无法得到正确的金额。有人可以帮忙吗?

标签: java

解决方案


在您的 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);
}

推荐阅读