Grades analyzer doesn't work


#1

Hello. Can anyone take a look at my code? It doesn't work. I get an error message
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 98, Size: 7
at java.util.ArrayList.rangeCheck(ArrayList.java:653)
at java.util.ArrayList.get(ArrayList.java:429)
at GradeAnalyzer.getAverage(GradeAnalyzer.java:18)
at GradeAnalyzer.main(GradeAnalyzer.java:38)

import java.util.ArrayList;

public class GradeAnalyzer{
 
  public GradeAnalyzer(){}
  
    public int getAverage(ArrayList<Integer>grades){
        if(grades.size() < 1){
            System.out.println("Array List is empty");
          return 0;
        }
        else{
             int sum = 0;
          // in order to get a value from an arraylist, you need to use the .get() function 
         for (Integer grade : grades){
          sum = sum + grades.get(grade); 
      // remember grades is the name of your arraylist
         }
 
      int average = sum / grades.size();
      System.out.println(average);
      return average;
        }
  }
  
  public static void main(String[] args){
  ArrayList<Integer> myClassroom = new ArrayList<Integer>();
    myClassroom.add(98);
    myClassroom.add(92);
    myClassroom.add(88);
    myClassroom.add(75);
    myClassroom.add(61);
    myClassroom.add(89);
    myClassroom.add(95);
  GradeAnalyzer myAnalyzer = new GradeAnalyzer();  
   myAnalyzer.getAverage(myClassroom);
    }
  
    
}

#2

Here you are already using a "for each" loop, so at each iteration grade is set to the current grade in the ArrayList grades. There's no need to use get, because you already have the value.