Kombo
Kombo

Reputation: 2381

Search method always null

I'm having issues with a method I've written to search a class called Item. No matter what I search, it is returning null. I believe I'm having issues with variable scope:

public Item search(String itemSearch) {
     Item search = null;
     for(Item i : items){
        if (i.getName() == itemSearch){
        search = i;
        }
     }
     return search;
  }

The getName method returns the name attribute of the item. No matter what the Item search is always null, I'm guessing this is due to variable scope and it is not assigning in the for each loop? Why is this method always null?

Thank you

Upvotes: 0

Views: 92

Answers (2)

Mr1159pm
Mr1159pm

Reputation: 774

You are comparing strings using ==. You should instead use equals() method. E.G

i.getName().equals(itemSearch)

Also instead of looping the entire loop use return i in the if statement, instead of assigning i to search and then returning search.

Upvotes: 2

Drahakar
Drahakar

Reputation: 6078

You can't use the == to compare the content of two strings in java. You need to use the .equals() method

Using the == will only compare the adress of the two strings, while equals will compare their values.

Upvotes: 4

Related Questions