Problem with For each loop


#1


Classroom Grades Analyzer

GradeAnalyzer.java:10: 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>();
    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

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;) .


#3

Thank you, that makes sense.


#4

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