0

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?

2 Answers 2

2

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.

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

1 Comment

An elegant solution! Cheers!
0

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;
}

Comments

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.