繁体   English   中英

如何在 java 中输入数组列表和 output 和

[英]How to input an array list and output sum in java

我有这段代码读取数组列表,直到用户输入 0 并计算数组的总和。 我的方式只读取了一半的输入。 请帮我检查并找出问题所在。 谢谢!!

Here is the supposed input and output (sample input) 1 2 3 2 1 0 (sample output from Eclipse - includes both input and output) This program will store numbers in an ArrayList and compute the sum of numbers. 一次输入一个数字。 输入 0 以终止输入。 1 2 3 2 1 0 ArrayList 中的项目为 [1.0, 2.0, 3.0, 2.0, 1.0] ArrayList 中的项目总数为 [1.0, 2.0, 3.0, 2.0, 1.0] ArrayList 中的项目总和为

这就是我正在做的事情

导入 java.util.ArrayList;

导入 java.util.Scanner; 公共 class SumArrayList {

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);

}

}

您正在使用nextDouble两次,因此它期望输入两倍

尝试

double value = scnr.nextDouble();
while(value != 0)
{
    list.add(value);
    value = scnr.nextDouble();
}

如果您只想要统计数据(而不是值),您可以完全放弃您的列表而只保留汇总。 就像是:

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

然后你就有了可用的计数、总和、平均值、范围。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM