java求和ArrayList值
到目前为止,我的程序允许用户输入,识别数组列表中存储了多少个数字,然后输出存储的数字。如何将用户输入的所有数字相加
import java.util.Scanner;
import java.util.ArrayList;
public class lab5
{
public static void main (String[]args)
{
Scanner userInput = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<>();
//Creates initial value for nextInt variable
int nextInt = -1;
//Create loop to store user input into array list until 0 is entered
while((nextInt = userInput.nextInt()) != 0)
{
list.add(nextInt);
}
//Calculate average once zero is inputted
if (nextInt == 0)
{
System.out.println("There are " + list.size() + " numbers in this array list");
System.out.println("The numbers are " + list);
System.out.println("The sum of the number are ")
}
}
}
# 1 楼答案
你很接近!输入到程序中的所有数字都将在某个时刻驻留在
nextInt
中。你怎么能利用这个事实得出总数呢?提示:您需要跟踪while
循环之外的总和