Learn Java Unit 4, Classroom Grades Analyzer: Exception in thread "main" java.lang.IndexOutOfBoundsException


#1

I am getting an error when I try running my code and I have no idea what it means. I've looked at others code and they seem to execute this last bit without problem.

Here's my code:

import java.util.ArrayList;

class GradeAnalyzer {
  
  public GradeAnalyzer(){
    
  }
  
  public int getAverage(ArrayList<Integer> grades){
    
    if (grades.size() < 1) {
      System.out.println("The ArrayList is empty.");
      return 0;
    } else {
      int sum = 0;
      for (Integer grade : grades) {
      sum += grades.get(grade);
      }
      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);
  }
  
}

Here's the error:

`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:17)
	at GradeAnalyzer.main(GradeAnalyzer.java:37)`

#2

Your problem is that you're trying to get the 98th element when there are only 7 elements.

Do you see why that's happening?


#3

I don't know if this is still a recurrent error but it has to do with the for each loop, grade is equal to the first number you entered which is 98 so when you use "grades.get(grade) is the same as "grades.get(98) which means that is looking for a value at index 98.

I had the same error, so I did a for loop and worked, Was I using the for each loop wrong?


#4

As it is an ArrayList and not a HashMap, you are just interested in the values.

      for (Integer grade : grades) {
      sum += grade;
      }

#5

I was stuck on the same thing. This was very helpful, thank you :smiley: