Being a noob, such a simple question i answered as soon as i posted :| - delete thread please.

Dani AI

Generated

As suggested, pulling the repeated check into a single boolean helper makes the original if much shorter and easier to read. Use a clear method name, handle null safely, and return early when a match is found so the loop stops as soon as possible. resolved the immediate issue, but the pattern below is useful when the same condition is checked across an array.

Example (simple, pre-Java‑8 style):

private static boolean anyCardMatches(Card[] cards) {
    if (cards == null) return false;
    for (Card card : cards) {
        if (card != null && matches(card)) { // replace matches(card) with the real check
            return true;
        }
    }
    return false;
}

Java 8+ alternative using streams:

boolean any = cards != null &&
              Arrays.stream(cards)
                    .filter(Objects::nonNull)
                    .anyMatch(c -> matches(c));

Notes and quick tips:

  • If the check is a simple equality against a small set of values, consider using a Set for O(1) membership tests instead of scanning the array repeatedly.
  • For reusable code, accept a Predicate<Card> so the helper can be reused for different checks:
    private static boolean anyMatch(Card[] cards, Predicate<Card> pred) { ... }
  • Add unit tests for the helper; it centralizes behaviour and makes edge cases (empty array, null elements) easier to cover.
  • Streams require Java 8+. For performance-sensitive loops, prefer the simple early-return loop.

Recommended Answers

All 2 Replies

You could write a boolean method that loops through your array, since for every card you're checking the same condition. Then your if statement becomes just a call to that method.

You could write a boolean method that loops through your array, since for every card you're checking the same condition. Then your if statement becomes just a call to that method.

Thanks reading my first post, i solved it pretty quick, just had a moment of panic i think :|

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.