Reputation: 3196
So the problem I'm running into is I want to test each part of an array against a condition, and if ALL the parts of the array return false I want to do something but if any of them return true I want to do something else. For example
String[] arr = new String[8];
for(String s : arr) {
if(s.equalsIgnoreCase("example") {
// Do this
} else {
// do that
}
}
The problem with the above is that is will do this or do that for all 8 pieces of the array. What I want is for it to test all of them, and if they're all false do that but if any of them are true then do this.
Upvotes: 0
Views: 106
Reputation: 468
The previous answer has the conditions backwards. It was testing if ANY is FALSE, "Do this" and if ALL are TRUE "Do that". Try this code:
String[] arr = new String[8];
boolean found = false;
for(String s : arr) {
if(s.equalsIgnoreCase("example")) {
found = true;
break;
}
}
if(found) {
// Do this
} else {
// Do that
}
Upvotes: 3
Reputation: 24447
You should extract the loop to another function say isSomeCondition( String[] someArr )
Upvotes: 0
Reputation: 51030
String[] arr = new String[8];
boolean isAllGood = true;
for(String s : arr) {
if(!s.equalsIgnoreCase("example") {
isAllGood = false;
break;
}
}
if(isAllGood) {
//do this
} else {
//do that
}
Upvotes: 5