1

How to calculate average grades (arithmetic method) in such a way that the extreme grades (6) will be removed from list - and the smallest (1) will be removed from list?

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);
    }
}
Bobulous
  • 12,967
  • 4
  • 37
  • 68
Martin
  • 31
  • 3

3 Answers3

1

You can add this simple code at the end of your previously written code:

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);     
abdulwasey20
  • 747
  • 8
  • 21
  • 1
    only one thing in the first line it should be "double" – Martin Feb 16 '19 at 16:54
  • that will only be required when your ArrayList is of type and you add decimal numbers in the array. Since you are adding whole numbers in the array only, their sum will also be a whole number always. So no need of "double" sum in this case. – abdulwasey20 Feb 16 '19 at 16:58
1

There is solution with stream api using Collectors::averagingDouble:

Double average = grades.stream()
            .collect(Collectors.averagingDouble(value -> value));
Ruslan
  • 6,090
  • 1
  • 21
  • 36
1

I tried something like this :

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