我正在尝试制作一个程序,从用户那里读取整数并将它们添加到列表中。当用户输入 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/