Java While loop extra conditions
In JavaScript you can add extra conditions like:
var b = 0.0; var q = (void 0); var e = -1.0; while(q = e, b > 32.0){ console.log(q); b++; }
Meaning that q equals to e.
I have tried to rephrase Java code to
Float b = 0.0; Float q = Float.NaN; Float e = -1.0; do{ q = e; b++; }while(b < 32.0);
But it seems that it doesn’t work as JS version.
Can I just add q = e to while conditions? Is there any valid Java syntax for it?
There is no comma operator in Java, and even if there was, it would be considered bad style.
There are ways you can achieve similar things. If you define a function that takes any parameter and always returns true:
<T> boolean trick(T any) { return true; }
you can use it to sneak in assignment expressions in any boolean context you want:
while (trick(q = e) && b > 32.0){ System.out.println(q); b++; }
But again, this would be considered terrible style. Don’t use this in a real project.
Java doesn’t have a hyperflexible comma operator like JavaScript so you’ll have to split the statements apart. That’s not a bad thing. while(q = e, b > 32.0)
is poor style.
Stick with a regular while
loop. A do-while
loop won’t do because it’ll always execute b++
at least once.
I would use double
rather than float
.
double b = 0.0; double q; double e = -1.0; q = e; while (b < 32.0) { b++; q = e; }
And we might as well initialize q
when it’s declared:
double b = 0.0; double e = -1.0; double q = e; while (b < 32.0) { b++; q = e; }