Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 506
Andreas Evjenth Avatar asked Dec 17 '25 22:12

Andreas Evjenth


2 Answers

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.

like image 52
Tunaki Avatar answered Dec 20 '25 11:12

Tunaki


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!

like image 36
Pato94 Avatar answered Dec 20 '25 11:12

Pato94



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!