如何将扫描仪输入整数存储在 Java 中,以便打印输入整数列表的总和?

How can I store the scanner input integers in Java so I can print the sum of a list of input integer numbers?

我正在做赫尔辛基大学的 Java MOOC,有一个练习要求我创建一个程序,让您可以输入任意数量的数字,但是当您输入“0”时它打印所有先前输入的数字的总和并结束程序。当您输入“0”时,我不知道如何 'store' 输入数字来计算它们的总和。该程序可以运行,但输入“0”会打印“0”。这是我的代码的样子:

public class Application {
public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("Input a number.");

    while (true) {
        try {
            int number = Integer.parseInt(scanner.nextLine());
            System.out.println("Input another number.");

            if (number == 0) {
                System.out.println(number + number);
                break;
            }
        }

        catch (NumberFormatException e) {
            System.out.println("Please input a valid number.");
        }
    }
}

如何计算所有输入数字的总和?

你可以创建一个计数器并像这样制作smth,你不需要保存所有数字:

  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int sum = 0;
    System.out.println("Input a number.");

    while (true) {
      try {
        int number = Integer.parseInt(scanner.nextLine());
        sum += number;
        System.out.println("Input another number.");

        if (number == 0) {
          System.out.println(sum);
          break;
        }
      }

      catch (NumberFormatException e) {
        System.out.println("Please input a valid number.");
      }
    }
 }

符合我上面的评论:

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int sum = 0;
        int number = -1;

        while (number != 0) {
            try {
                System.out.print("Input a number (0 to quit): ");
                number = Integer.parseInt(scanner.nextLine());
                sum += number;
            }
            catch (NumberFormatException e) {
                System.out.println("Please input a valid number.");
            }
        }
        System.out.println("Total:" + sum);
    }