0

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.

3
  • Just create boolean variables representing both conditions. Then, depending on the result of the initial condition a select the corresponding variable. Commented Feb 21, 2018 at 0:44
  • @Zabuza depends whether a changes within the loop or not. Commented Feb 21, 2018 at 0:46
  • 1
    @Aominè Good point. Commented Feb 21, 2018 at 0:50

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2
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...

5 Comments

My example is not exactly the code I have. The for loop needs to change itself midway through.
@PTwno well, this would work; it's just very difficult to follow.
@PTwno What do you mean by "change itself"? Like changing direction? 50 up 50 down?
Better to restructure into two consecutive loops, even if this means pulling out the body into a method.
@LouisWasserman probably. I considered adding that to my answer when I wrote it, but decided against it because we don't know what is going on in and around the loop, how 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.