0

I have a method in each of my employee subclasses that calculates their earnings and returns that value. In my main method I want to add 200 to this value if the employee has been in the workplace for over 5 years. My approach was to compare the date that the employees joined to the current date by looping through my array of different employees and checking if it has been more than 5 years. If so, I want to get the employees earnings and add 200 to it.

I get an error at employeeArray.get(i).earnings() += 200; -> "Variable expected"

Relevant Code:

Test Class

for(int i = 0; i < employeeArray.size(); i ++){
            if(employeeArray.get(i).getDateJoined().compareTo(LocalDate.of(2015, 10, 16)) <= 0)
                {
                    employeeArray.get(i).earnings() += 200;
                }
            }

Employee Class

    public abstract double earnings();

Example employee (boss) earnings method (Subclass to Employee)

 public double earnings() {
        try{
            if(weeklySalary < 100){
                throw new Exception();
            }
        }
        catch (Exception lowWageException){
            System.out.println();
        }
        return weeklySalary;
    }
B.brown
  • 21
  • 5
  • I just want to double check: `In my main method I want to add 200 to this value if the employee has been in the workplace for over 5 years.` Are you sure? Because this sort of thing would be an excellent choice to encapsulate within the class. Using an external check to do it seems wrong. Check with your instructor that this is what they want. – markspace Oct 21 '20 at 14:56
  • Note: question is similar to this, although the error messages are different. https://stackoverflow.com/questions/15291861/why-doesnt-the-post-increment-operator-work-on-a-method-that-returns-an-int – markspace Oct 21 '20 at 15:09

1 Answers1

3
employeeArray.get(i).earnings() += 200; 
-> "Variable expected"

Yes, some expressions can occur on the left side of an assignment, some cannot.

For example,

a = 5;

is ok, but

a + 1 = 5;

is not. A method call (like earnings()) is one of those things that cannot appear on the left side of an assignment.

For this, you need a setter (or something similar) that takes a value so you can set the earnings.

public void setEarnings( double earn ) {
   weeklySalary = earn;
}

Then you can call that to set the value of weeklySalary.

if(employeeArray.get(i).getDateJoined()
      .compareTo(LocalDate.of(2015, 10, 16)) <= 0)
{
   double temp = employeeArray.get(i).earnings() + 200;
   setEarnings( temp );
}
markspace
  • 10,621
  • 3
  • 25
  • 39