Grade Analyzer: Missing return statement


#1



https://www.codecademy.com/en/courses/learn-java/projects/grades-analyzer


GradeAnalyzer.java:23: error: missing return statement
}
^
1 error


//Not sure what the issue is, I checked to see that every single bracket had a pair

import java.util.ArrayList;

class GradeAnalyzer {
  public GradeAnalyzer(){
  }
  
  public int getAverage(ArrayList<Integer> grades) {
   
    if (grades.size() < 1){
      System.out.println("Please input an array of size greater than 0.");
    }
    else {
      int sum = 0;
      for(Integer grade : grades){
        sum = sum+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);
    
  }
}


#2

Inside of the if block, print out a friendly error message to the user indicating that the ArrayList is empty. On the next line, return 0.

This is actually quite important, else there is no return for that state (empty array), which leads to the error that has been thrown.

Here is a spoiler for you to compare with. I just did this exercise and got the expected 85 in the console.


import java.util.ArrayList;
class GradeAnalyzer {
  public GradeAnalyzer () {
    
  }
  public int getAverage (ArrayList<Integer> grades) {
    if (grades.size() < 1) {
      System.out.println ("Input Error: No data");
      return 0;
    } else {
      int sum = 0;
      for (int grade : grades) {
        sum += 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(96);
    GradeAnalyzer myAnalyzer = new GradeAnalyzer();
    myAnalyzer.getAverage(myClassroom);
  }
}

#3

Oh I see, I totally missed the fact that it was declared as an int return. Thank you!


#4

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