0

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.

3 Answers 3

5
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
}
Sign up to request clarification or add additional context in comments.

1 Comment

This example has the conditions backwards and won't work the way that is desired.
3

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
}

2 Comments

I literally just finished editing the other answer to reflect the conditions the correct way :P thanks
That's because my edit needs to be peer reviewed... I'll mark this one as correct since it's correct without edits needed.
0

You should extract the loop to another function say isSomeCondition( String[] someArr )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.