为了账号安全,请及时绑定邮箱和手机立即绑定

将用户输入的元素总和输出到 ArrayList Java

将用户输入的元素总和输出到 ArrayList Java

温温酱 2021-10-28 15:38:06
我目前正在编写一个 java 代码,它从用户那里获取输入并输出 arraylist 的大小、输入的数字总和、输入的平均值和最大数量。我无法完成总和,因为 for 循环没有计算结果。我将不胜感激任何建议。我的代码如下。import java.util.ArrayList;import java.util.Scanner;public class Main {    public static void main(String[] args) {        // write your code here        double size = 0;        double a = -999;        double total = 0;        Scanner in = new Scanner(System.in); // scanner object for user input        ArrayList<Double> inputs = new ArrayList<Double>();        System.out.println("Enter a number, to terminate enter -999 :");        while (in.hasNextDouble()) {            //assign the nextDouble to a variable            double tmp = in.nextDouble();            //test the variable            if (tmp != a) {                //add the variable                //if you want to add -999 to the inputs then this next line above the test.                inputs.add(tmp);                System.out.println("Enter a number, to terminate enter -999 :");            } else {                inputs.size(); // get size of input                System.out.println("Numbers entered: " + inputs.size());                break;            }        }        for (double sum : inputs) {            total += sum;            System.out.println("The sum of numbers entered is " + total);            break;        }    }}
查看完整描述

2 回答

?
慕勒3428872

TA贡献1848条经验 获得超6个赞

将break在for循环将导致循环退出。在这里,它导致循环在第一次迭代时退出,这几乎肯定不是您想要的。


将println外部移动到循环中,并删除break:


for (double sum : inputs) {

    total += sum;

}


System.out.println("The sum of numbers entered is " + total);

这允许for循环在计算总和时迭代整个列表,以便您可以打印它而不是过早退出。


还要注意的是:


inputs.size(); // get size of input

做什么都没有用。size返回 的大小inputs,然后您对该数字不执行任何操作,因此它丢失了。您应该删除该行,因为size无论如何您都会在下一行再次调用。


查看完整回答
反对 回复 2021-10-28
  • 2 回答
  • 0 关注
  • 192 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信