Hamed Afshar
Hamed Afshar

Reputation: 183

Android java for loop breaks suddenly

I have the following code running:

public static Level getNextLevel(Context context, int id)
{
    boolean found = false;
    ArrayList<Level> levels = getLevels(context);
    for(Level lvl : levels)
    {
        if (found)
        {
            return lvl;
        }
        if (lvl.id==id)
        {
            found=true;
        }
    }
    return null;
}

When I trace it, the second if works and variable found becomes true, then another iteration goes and when it gets to line "if (found)", I check and variable found is true, but it then breaks of the for block instead of going into the if block!

The ArrayList levels has 5 items and it happens just after the first item is checked.

Any suggestions why this might happen?

Upvotes: 1

Views: 114

Answers (5)

Talha
Talha

Reputation: 699

Your code is looking good

    boolean found = false;
    ArrayList<Level> levels = getLevels(context);
    for(Level lvl : levels)
    {
        if (found)
        {
            return lvl;
        }
        if (lvl.id==id)
        {
            found=true;
        }
    }
    return null;

You may try following loop for what you are trying to achieve

for(int i=0; i<levels.size()-1; i++){
   if(levels.get(i).id ==id )
   {
     return levels.get(i+1);
   }


}

Upvotes: 0

Hartmut Pfitzinger
Hartmut Pfitzinger

Reputation: 2306

Your method getNextLevel() tries to yield the successor of the entry in ArrayList<Level> levels which is equal to id. But if id matches the last entry then the for-loop ends and you get null.

Upvotes: 1

Yazan
Yazan

Reputation: 6082

FYI the returned "l" is not the found "l" because it is returned in the next loop, which is the next item in the arraylist

anyways, i suggest you method to be like this

public static Level getNextLevel(Context context, int id){
    //boolean found = false; no need
    ArrayList<Level> levels = getLevels(context);
    for(Level lvl : levels)
    {
        if (lvl.id==id)
        {
             return lvl ;
        }
    }
    return null;
}

i replaced l with lvl to make it clear, it looks 1 and l looks similar on some fonts.

Upvotes: 0

Simas
Simas

Reputation: 44118

EDIT: After examining your question further it seems that you will want to remove return 1; entirely. As your for loop actually enters the if (found) block but return forces it to exist the loop and the whole method.

Upvotes: 0

David Ferrand
David Ferrand

Reputation: 5470

You say that found becomes true at the first iteration, then logically the next iteration will enter the first if and call return l, which means your loop will stop.

So the question is: should the first iteration have set found to true?

Upvotes: 0

Related Questions