java - 如何在数组列表中总结用户的输入?

标签 java arraylist

我正在尝试制作一个程序,从用户那里读取整数并将它们添加到列表中。当用户输入 0 时,此过程结束。然后程序将总和打印在列表上。

我的代码可以工作,但问题是总和值没有正确相加

public class Main {
        private static Scanner input = new Scanner (System.in);
    public static void main(String[] args) {

    ArrayList<Integer> test1 = new ArrayList<Integer>();
    System.out.println("Enter multiple numbers"); //if user enters =0; loop ends


    while (input.nextInt() != 0) {
        test1.add(input.nextInt());
        input.nextLine();
    }

    int total = 0;
    for(int x : test1){
        total+=x;
    }
    System.out.println(total);
}
}

最佳答案

您仅在循环中存储每第三个值。这个

while (input.nextInt() != 0) {
    test1.add(input.nextInt());
    input.nextLine();
}

应该是这样的

int value;
while ((value = input.nextInt()) != 0) {
    test1.add(value);
}

while (input.hasNextInt()) {
    int value = input.nextInt();
    if (value == 0) {
        break;
    }
    test1.add(value);
}

关于java - 如何在数组列表中总结用户的输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61585283/

相关文章:

java - JConsole Web 应用程序

java - 如何将Arraylist数据转换为Vector类型?

android - 具有优先级 ID 和日期时间的排序列表模型

java - 列表的二维数组

java - SharedPreferences Android 中奇怪的无法解释的行为

java - 使用递归查找堆栈中的最小值

java - 使用 Lucene 进行精确短语搜索?

java - 打印 4 x 5 板的所有配置,其中包含 1's and 0' s,尽可能不包含三个 1's in a row or diagonally, while filling as many 1' s

java - 安卓/Java : Check if arraylist is empty and then launch another activity

java - 解析文本文件的最简洁方法