如何将用户的输入求和存储在ArrayList中?

huangapple 未分类评论47阅读模式
英文:

How to sum up user's input in 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("输入多个数字"); // 如果用户输入 = 0; 循环结束

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

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

I am trying to make a program that reads integers from the user and adds them to a list. This ends when the user enters 0. The program then prints the sum on the list.

My code works but the problem is the sum value does not add up correctly

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

    ArrayList&lt;Integer&gt; test1 = new ArrayList&lt;Integer&gt;();
    System.out.println(&quot;Enter multiple numbers&quot;); //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);
}
}

答案1

得分: 0

你的循环中仅存储每第三个值。这段代码:

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);
}
英文:

You are only storing every third value in your loop. This

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

should be something like

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

or

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

huangapple
  • 本文由 发表于 2020年5月4日 12:39:31
  • 转载请务必保留本文链接:https://java.coder-hub.com/61585283.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定