Problem with For each loop


Classroom Grades Analyzer error: variable sum is already defined in method getAverage(ArrayList)
int sum = grades.get(i);
1 error

Hello, I cant understand why does this for loop not work, as I understand it should be the same..? I know I made a misstake somewhere there because it works with shorter version (commented).

import java.util.ArrayList;
public class GradeAnalyzer {
  public int getAverage(ArrayList<Integer>grades){
    if (grades.size() <= 1) {
     System.out.println("No grades entered!");
      return 0;
    } else {
      int sum = 0;
/*    	for (Integer grade : grades){
        	sum = sum + grade;
      } */
      for (int i = 0; i < grades.size(); i++){
      int sum = sum + grades.get(i);
      int average = sum / grades.size();
      System.out.println("Average of grades: " + average);
      return average;
  public static void main(String[] args){
     ArrayList<Integer> myClassroom = new ArrayList<Integer>();
    GradeAnalyzer myAnalyzer = new GradeAnalyzer();


You declared the variable sum twice, by putting the int before the sum = 0; in the beginning and then again later in int sum = sum + grades.get(i);.
By declaring the variable as int twice the compiler thinks you're trying to make two variables both named sum in the same method, which causes an error. You can only define it once in the same method, if you want to use it again you just put the variable name (not it's type) and it's new value
( sum = 0;) .


Thank you, that makes sense.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.