Reputation: 1
I am trying to create a method that returns true if the two parameters (user-inputted) are in the arrayList. When my code runs it always returns false when it should be true
public boolean containsItem(String targetTitle, String targetAuthor){
boolean result= false;
for (MediaItem contains : itemList) {
if(contains.getTitle().equals(targetTitle) && contains.getAuthor().equals(targetAuthor)) {
result = true;
}else{
result = false;
}
}
return result;
}
Do I need two separate if statements or loops? I am not sure why it keeps returning false. I have also tried if(contains.equals(targetTitle) && contains.equals(targetAuthor)) {
Upvotes: 0
Views: 44
Reputation: 87
public boolean containsItem(String targetTitle, String targetAuthor){
boolean result= false;
for (MediaItem contains : itemList) {
if(contains.getTitle().equals(targetTitle) && contains.getAuthor().equals(targetAuthor)) {
result = true;
break;
}
return result;
}
Not sure what getTitle() means here, and if it should be equalsIgnoreCase() is up to you, but this should work.
Upvotes: 0
Reputation: 54168
You don't need the result = false
part, if you find at a moment, just keep to true and that's it. Also to get quicker, when you find a true : just stop, no need to continue, so you can use a break
to stop looping, or just return
directly :
public boolean containsItem(String targetTitle, String targetAuthor){
for (MediaItem contains : itemList) {
if(contains.getTitle().equals(targetTitle) && contains.getAuthor().equals(targetAuthor)) {
return true;
}
}
return false;
}
Upvotes: 2