jeudi 15 mars 2018

Series of if statements are not returning an int value (Java)

I want to compare two objects of Manager using three variables, deptNum, firstName and then lastName. I have set up these objects to be compared using a series of if and if-else statements. The error I am receiving is that the valReturn variable may not have been initialized, which I assume means an if statement somewhere along the way is not assigning a value correctly. I'm not sure where I made a mistake.

If there is a more efficient way to set up this comparison, I would be happy to be educated further.

Thank you.

Below is my code:

public class ManagerComparator implements Comparator<Manager> {
public int compare(Manager first, Manager second) {
    int valReturn;
    if (first.getDeptNum() < second.getDeptNum())
        valReturn = -1;
    else if (first.getDeptNum() > second.getDeptNum())
        valReturn = 1;
    else if (first.getDeptNum() == second.getDeptNum()) {
        if (first.getFirstName().compareTo(second.getFirstName()) < 0)
            valReturn = -1;
        else if (first.getFirstName().compareTo(second.getFirstName()) > 0)
            valReturn = 1;
        else if (first.getFirstName().compareTo(second.getFirstName()) == 0) {
            if (first.getLastName().compareTo(second.getLastName()) < 0)
                valReturn = -1;
            else if (first.getLastName().compareTo(second.getLastName()) > 0)
                valReturn = 1;
            else if (first.getLastName().compareTo(second.getLastName()) == 0)
                valReturn = 0;
        }
    }
    return valReturn;
  }
}

Aucun commentaire:

Enregistrer un commentaire