RESOLVED: So I have this code that returns the highest payed employee. But it wont compile and I get the error message, 'variable employee might not have been initialized'.
/** * Locates and returns the employee that earned the most * @return Employee object that earned the most */ public Employee highestPayedEmployee() { double leastAmount = 0.0; Employee employee; for(Employee e : employeeList){ if(leastAmount <= e.calculateMonthlyPay()){ leastAmount = e.calculateMonthlyPay(); employee = e; } } return employee; }
So then I tried putting the definition of that variable in the if statement, but I get the error, cannot find symbol - variable employee. I'm guessing because since its in the if statement it may not actually reach it. So I just tried putting it outside the if statement in the for loop, like this for testing purposes:
public Employee highestPayedEmployee() { double leastAmount = 0.0; // Employee employee; for(Employee e : employeeList){ if(leastAmount <= e.calculateMonthlyPay()){ leastAmount = e.calculateMonthlyPay(); } Employee employee = e; } return employee; }
Then I get that error again, cannot find symbol - variable employee.
So the only option to make this work at all was to do this..
public Employee highestPayedEmployee() { if(!employeeList.isEmpty()){ double leastAmount = 0.0; Employee employee = employeeList.get(0); for(Employee e : employeeList){ if(leastAmount <= e.calculateMonthlyPay()){ leastAmount = e.calculateMonthlyPay(); employee = e; } } } return employee; }
Is this the correct way to be doing this? It seems an odd way to do it, I got stuck on a test trying to figure this out!
Thanks