0

I'm trying to find an element in the ArrayList "minions" with the highest "evilLevel" (that's defined in another class).

public Minion(String name, int evilLevel, boolean onMission) - from class Minion


    private Set<Minion> minions;
    int maxEvilLevel = 0;
    Minion theMostEvilMinion;  

     public MinionRegister(){


        minions = new HashSet<Minion>();
      }

     public Minion getMostEvilMinion(){
        if(minions.isEmpty()){
            return null;
        }


        for(Minion m : minions){
            if(m.getEvilLevel() > maxEvilLevel) {
                maxEvilLevel = m.getEvilLevel();
                Minion theMostEvilMinion = m;
            }
        }
        return theMostEvilMinion;
    }

Unfortunately the method returns "null"

3
  • This code won't compile. Please have a look around and read through the help center. In particular How do I ask a good question? Commented Mar 27, 2019 at 16:37
  • You say ArrayList, but your code is using a HashSet. They are not the same thing. Commented Mar 27, 2019 at 16:45
  • Oh, right, originally I think I was using ArrayList but then switched to HashSet and got slightly lost in the meantime. Commented Mar 27, 2019 at 16:48

1 Answer 1

2

Here:

for(Minion m : minions){
    if(m.getEvilLevel() > maxEvilLevel) {
        maxEvilLevel = m.getEvilLevel();
        Minion theMostEvilMinion = m;
    }
}
return theMostEvilMinion;

Inside the for loop, you declaring and setting a local variable theMostEvilMinion, which is then forgotten, because it is declared inside that block.

Then after the loop, you return the instance variable theMostEvilMinion, a different variable which is declared at the top of your class.

You need to declare and set one local theMostEvilMinion variable and then return it.

Minion theMostEvilMinion = null;
int maxEvilLevel = 0;
for (Minion m : minions) {
    if (m.getEvilLevel() > maxEvilLevel) {
        maxEvilLevel = m.getEvilLevel();
        theMostEvilMinion = m;
    }
}
return theMostEvilMinion;

Then you can also delete the theMostEvilMinion and maxEvilLevel instance variables.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.