Error in my code


#1



This is the error message i am getting.

GradeAnalyzer.java:20: error: cannot find symbol
int average = sum / grades.size();
^
symbol: variable sum
location: class GradeAnalyzer
1 error


import java.util.ArrayList;

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

Keep in mind that variables aren't global, you can only access variables in the current or surrounding scopes. (And they are destroyed when their scopes exit)


#3

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