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.
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.
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...
a changes etc. I figured it was better to answer the direct question, and express mild disparagement to hint that it is maybe not the best way to approach it.
booleanvariables representing both conditions. Then, depending on the result of the initial conditionaselect the corresponding variable.achanges within the loop or not.