C Hill
C Hill

Reputation: 37

Looping through an Array and performing a different action after the first match?

As I've tried to structure below, I want an if statement that performs in a for loop to do one thing the first time it is processed, and something else every other time.

if (true) {
    for (value i : valueList) {
        if (i = true) {
             First time do this!
             Second time onwards do this!
         }

    }
}

Is there a function in java that allows me to do this?

Upvotes: 2

Views: 159

Answers (1)

Bohemian
Bohemian

Reputation: 425128

I've always used a flag, which gets unset in the first block to turn it off:

boolean first = true;
for ( value i : valueList ) {
    if ( i ) {
        if (first) {
            // First time do this!
            first = false;
        } else {
            // Second time onwards do this!
        }
    }
}

Note I removed the buggy assignment if (i = true) which is always true, and assigns true to i (clobbering your loop variable's value).

Also, the outer if (true) is unnecessary.

Upvotes: 8

Related Questions