vendredi 4 décembre 2015

for each loop (Java) [duplicate]

This question already has an answer here:

I have searched around for an answer but everywhere I look says I should be right. It must be something simple.

'heldItems' is an arrayList of type 'Item'. Each Item has a String, String, int, boolean.

For some reason I am getting the message that is written in the else statement. I know for a fact that the item I am looking for is inside the arrayList, meaning my program should display the message written in the if statement. That makes me think I am looping wrong or my if statement is wrong.

The string being provided is the name (first string in each Item)

My code

public void drop( String name )
{
    for (Item i : heldItems)  
    {            
        if (i.getName() == name )
        {
            currentRoom.setItem(i);  //adds Item i to the room.
            heldItems.remove(i) ;    //removes i from heldItems.
            message = ""      
        }   

        else
        {
          message = "put message here";  
        }
    }
}

Please let me know if you need more information, I am very knew to Java and programming in general. Thank you.

Aucun commentaire:

Enregistrer un commentaire