Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeat iteration in enhanced-for loop

Tags:

java

for-loop

Regular for-loop

for (int i = 0; i < 10; i++) {
    // ...

    if (iWantToRepeat) {
        i--;
        continue;
    }

    // ...
}

Enhanced for-loop

for (Foo f : Bar) {
    // ...

    if (iWantToRepeat) {
        // What can I put here?
    }

    // ...
}

Is there any way to repeat an iteration of an enhanced for-loop? I get the feeling there might be because it's based on iterators and if I had access to them I could do it I think.

like image 355
Ogen Avatar asked Dec 14 '22 21:12

Ogen


1 Answers

No, you can't. In every iteration the Iterator procedes by 1 step. However you can use a do-while loop to get the same effect:

for (Foo f : Bar) {
    boolean iWantToRepeat;
    do {
        // ...
        iWantToRepeat = //...;
        // ...
    } while(iWantToRepeat);
}
like image 177
fabian Avatar answered Dec 17 '22 10:12

fabian