unexpected return value when computing average?

bretth18 picture bretth18 · Jan 30, 2015 · Viewed 11.6k times · Source

I am having trouble being able to return the value of the "average" variable in my getter method. I keep getting the error "incompatible types: unexpected return value" but the value is defined above in the setter method?

I looked for a similar issue but could not find anything close to this

public class Student {

    private String firstName;
    private String lastName;
    private int score1, score2, score3;
    private int average;



      public void setFirstName(String name){
      firstName = name;
    }
      public String getFirstName(){
      return firstName;
    }
      public void setLastName(String name){
      lastName = name;
    }
      public String getLastName(){
      return lastName;
    }
      public void setScore1(String newvalue){
      score1 = Integer.parseInt(newvalue);
    }
      public int getScore1(int newvalue){
      return score1;
    }
      public void setScore2(String newvalue){
      score2 = Integer.parseInt(newvalue);
    }
      public int getScore2(int newvalue){
      return score2;
    }
      public void setScore3(String newvalue){
      score3 = Integer.parseInt(newvalue);
    }
      public int getScore3(int newvalue){
      return score3;
    }
      public int setAverage(int newvalue){
      average = (score1 + score2 + score3)/3;
    }
      public void getAverage(String newvalue){
      return average;
    } 
}

Answer

Am_I_Helpful picture Am_I_Helpful · Jan 30, 2015

Because your getAverage(String newvalue) method has a function definition consisting of return type as void and you're returning value from that method.

Any method having return type set as void in the function definition/declaration isn't supposed to return any value.

Please correct it as :-

public int getAverage(String newvalue){
  return average;