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.
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With