In the expression of a while loop, is it possible to initialise a variable, then use that as part of the expression?
It’s probably simpler in code:
while (int a = someMethod(), a<b)
It would be possible to just add another method, and so have to following:
private boolean whileLoopTest() {
int a = someMethod();
return a<b;
}
public void originalMethod() {
while (whileLoopTest()) {
//...
but this doesn’t seem as neat.
EDIT
I also don’t want to directly compare the method to my variable, as it is compared to several variable, and so if would be a long, unreadable mess. A better example of what I want would be:
while (int a = SomeClass.someStaticMethod(), -1<a && a<b)
It’s not true in my case, but this would be a equally valid question if someStaticMethod() took a long time to return – I would only want to call it once.
I’m fairly new to StackOverflow, so I’m not sure if giving other situations where this would apply is what I should be doing.
A common use for this is reading from a file:
/edit
You can do this for your new scenario:
Once the left hand portion of the
&&statement is executed, the return value ofSomeClass.staticMethod()is stored ina, which carries over the the right hand portion of the statement.