英文:
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<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);
}
}
答案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);
}
专注分享java语言的经验与见解,让所有开发者获益!
评论