如何在java中输入数组列表并输出总和

如何在java中输入数组列表并输出总和,java,arrays,Java,Arrays,我有一段代码,它读取数组列表,直到用户输入0并计算数组的和。我的方式只能读取一半的输入。请帮我检查一下,看看出了什么问题。谢谢 这里是假定的输入和输出 (样本输入) 1 2 3 2 1 0 (Eclipse的示例输出-包括输入和输出) 该程序将数字存储在ArrayList中,并计算数字之和。 一次输入一个数字。输入0以终止输入。 1 2 3 2 1 0 ArrayList中的项目是[1.0,2.0,3.0,2.0,1.0] ArrayList中有5项 ArrayList中的项之和为9.0 这就是

我有一段代码,它读取数组列表,直到用户输入0并计算数组的和。我的方式只能读取一半的输入。请帮我检查一下,看看出了什么问题。谢谢

这里是假定的输入和输出 (样本输入) 1 2 3 2 1 0 (Eclipse的示例输出-包括输入和输出) 该程序将数字存储在ArrayList中,并计算数字之和。 一次输入一个数字。输入0以终止输入。 1 2 3 2 1 0 ArrayList中的项目是[1.0,2.0,3.0,2.0,1.0] ArrayList中有5项 ArrayList中的项之和为9.0

这就是我正在做的

导入java.util.ArrayList

导入java.util.Scanner; 公共类SumarayList{

public static void main(String[] args) {
    Scanner scnr = new Scanner(System.in);
    ArrayList<Double> list = new ArrayList<Double>();
    int n=0;
    double sumVal = 0;
    System.out.println("This program will store numbers in an ArrayList and compute the sum of numbers.\r\n" + 
            "Enter the numbers one at a time. Enter a 0 to terminate the input.");
    while(scnr.nextDouble() != 0)
    {
        list.add(scnr.nextDouble());
    }
    System.out.print("The items in the ArrayList are ");
    for(int i=0; i < list.size(); i++)
    {
        System.out.print(list.get(i) + " ");
        sumVal += list.get(i);
        n = i+1;
    }
    System.out.println();
    System.out.println("There are " + n + " items in the ArrayList");
    System.out.println("The sum of " + n + " items in the ArrayList is " + sumVal);

}
publicstaticvoidmain(字符串[]args){
扫描仪scnr=新扫描仪(System.in);
ArrayList=新建ArrayList();
int n=0;
双总和=0;
System.out.println(“此程序将在ArrayList中存储数字并计算数字之和。\r\n”+
“一次输入一个数字。输入0以终止输入。”);
while(scnr.nextDouble()!=0)
{
list.add(scnr.nextDouble());
}
System.out.print(“ArrayList中的项目为”);
对于(int i=0;i

}

您正在使用
nextDouble
两次,因此它需要两次输入

试一试


如果你只想要统计数据(而不是值),你可以完全放弃你的列表,只保留聚合数据。比如:

DoubleSummaryStatistics stats = DoubleStream.generate(scnr::nextDouble)
    .takeWhile(d -> d > 0).summaryStatistics();
然后就有了计数、总和、平均值和范围

DoubleSummaryStatistics stats = DoubleStream.generate(scnr::nextDouble)
    .takeWhile(d -> d > 0).summaryStatistics();