如何从数组列表中提取数字,将它们相加并除以数组列表中的数字数量?

How to extract numbers from an array list, add them up and divide by the amount of numbers in the array list?

我在网上看了一节关于数组的课。它教会了我 'basics' 数组列表:如何创建数组列表。所以我想知道,如何根据用户输入 (JOptionPane) 创建一个数组列表,从中提取数字,将它们相加并除以数组列表中的数字总数 (长话短说,计算数组的平均值)?

这是我的一种方法:

import java.util.Arrays;
import javax.swing.JOptionPane;
public class JOptionPaneTesting {

    public static void main(String[] args){
        int grades = Integer.parseInt(JOptionPane.showInputDialog("What are your grades of this month?"));
        int arrayList[] = {Integer.valueOf(grades)};
        int arraysum;
        arraysum = arrayListGetFirstIndex + arrayListGetSecondIndex + ...; //Extracts all of the indices and adds them up?
        int calculation;
        calculation = arraysum / arrayListAmmountOfNumbersInTheList; //An example of how it go about working
    }
}

首先创建一个列表

List<Integer> list = new ArrayList<Integer>();`

然后list.add(grade); 如果要添加多个等级,则需要遍历整个行。 然后 list.get(index) 给你特定的(指数)等级。

计算 arraySum 使用:

for(int i = 0; i < list.size() ; i++)
    arraysum += list.get(i); // and others are same.

希望对您有所帮助!

据我了解这个问题,您正在尝试从用户那里获取输入。输入是成绩。然后你想把成绩相加并计算成绩的平均值。

public static double calculateAvg(List<Double>inputGrades){
        List<Double> grades = new ArrayList<Double>(inputGrades);
        double totalScore = 0.0;
        double avgScore = 0.0;
        if(grades !=null && grades.size()>0){
            for(Double grade : grades){
                totalScore = totalScore + grade;
            }
        avgScore = totalScore / grades.size();
        }

        return avgScore;
    }

获取用户输入并将其添加到列表

List<Double> gradesList= new ArrayList<Double>();
                gradesList.add(25.5);
                gradesList.add(29.5);
                gradesList.add(30.5);
                gradesList.add(35.5);
        System.out.println(calculateAvg(gradesList));

这也是一个合适的解决方案:

String[] input = JOptionPane.showInputDialog("What are your grades of this month?").split(" ");
        double[] grades = new double[input.length];
        double average = 0.0;
        for (int i = 0; i < input.length; i++) {
            // Note that this is assuming valid input
            grades[i] = Double.parseDouble(input[i]);
            average+=grades[i];
        }
        average /= grades.length;

因此您可以输入多个 "grades",用空格分隔。