PTwno
PTwno

Reputation: 41

Implementing a conditional for loop

Is there a way to do something like this in Java?

for (int i = 0; if (a) { i < x } else { i < y }; i++) { ... }

Thanks in advance.

Upvotes: 0

Views: 61

Answers (2)

Zabuzard
Zabuzard

Reputation: 25903

A clean approach would be to store the bounds in int variables and then select the corresponding variable based on the initial condition:

int bound;
if (a) {
    bound = x;
} else {
    bound = y;
}

for (int i = 0; i < bound; i++) {
    ...
}

You can use the ternary operator for that kind of assignment like

int bound = a ? x : y;

Or directly inside the for loop:

for (int i = 0; i < (a ? x : y); i++) {
    ...
}

Be aware that, with the first approach, the condition will only be evaluated once. If it can change inside the loop you will need to update it inside.

Upvotes: 3

Andy Turner
Andy Turner

Reputation: 140318

for(int i = 0; a ? (i<x) : (i<y); i++){}

or

for(int i = 0; i < (a ? x : y); i++){}

It must be asked why you'd want to...

Upvotes: 2

Related Questions