Andreas Evjenth
Andreas Evjenth

Reputation: 500

Is it possible to make the variable increases or decreases in a for-loop based on a boolean in Java?

I know it is easily achievable through an if/else-statement with two different for-loops, but what I'm asking about is if it's possible to do something like:

for(int a = 0; a < value ; boolean ? a++ : a--){
}

But that only leaves the error "not a statement" in my compiler.

EDIT: The a<value isn't a big issue. I'm okay with this being an infinite loop in both directions with a break-condition inside the for-loop.

Upvotes: 2

Views: 601

Answers (2)

Pato94
Pato94

Reputation: 804

Yes, you can do it.

The third statement in a for-loop it's just an expression that evaluates once per iteration. You're getting a compilation error because the ternary operator needs an assignment in order to be valid.

boolean ? a++ : a--

Instead here's another way of doing the same

boolean b = true;
int a = 0;
for (; a < value; a = b ? a + 1 : a - 1) {
    //Your code
}

Hope this helps!

Upvotes: 1

Tunaki
Tunaki

Reputation: 137174

Yes, you can technically use a ternary operator in the [ForUpdate] part of a for loop. The syntax for it would be:

for (int a = 0; a < value; a += bool ? 1 : -1){
    // ...
}

where bool is of type boolean. It will either increment or decrement a depending on whether bool is true or not.

Upvotes: 10

Related Questions