ArrayList整数-在不考虑极值的情况下计算平均成绩

时间:2019-02-16 16:27:07

标签: java algorithm average

如何计算平均成绩(算术方法),以使极端成绩(6)从列表中删除,而最小成绩(1)从列表中删除?

import java.util.*;
import java.lang.*;
import java.io.*;

class ListOfGrades
{
    public static void main (String[] args) throws java.lang.Exception
    {
        //Create and fill the list 
        ArrayList<Integer> grades = new ArrayList<Integer>();
        grades.add(1);
        grades.add(2);
        grades.add(3);
        grades.add(4);
        grades.add(5);
        grades.add(6);

        for(int i=0; i < grades.size(); i++) {
            System.out.println("Element : [" + i + "] grades " +  grades.get(i)) ;  
        }
        System.out.println();
        System.out.println("Removing last Element");
        grades.remove(grades.size()-1);
        System.out.println("Now all grades are : " + grades);
        System.out.println();
        System.out.println("Removing first Element");
        grades.remove(grades.size()-5);
        System.out.println("Now all grades are : " + grades);
    }
}

3 个答案:

答案 0 :(得分:1)

您可以在以前编写的代码的末尾添加以下简单代码:

int sum=0;
for (int i=0; i<grades.size();i++){
    sum+=grades.get(i);               //adding all the grades in variable sum
}
double avg= sum/grades.size();      //dividing the sum with total number of 
                                    //grades to calculate average
System.out.println("average grade :" + avg);     

答案 1 :(得分:1)

有使用Collectors::averagingDouble的流api解决方案:

Double average = grades.stream()
            .collect(Collectors.averagingDouble(value -> value));

答案 2 :(得分:1)

我尝试过这样的事情:

 grades.stream().filter(g -> !(g == 1 || g == 6))
                   .reduce((grade, sum) -> grade + sum)
                   .map(sum -> sum / 4)
                   .orElse(0);