When the following code is run it won't compile and I get an error telling me, "Found one too many { characters without a } to match it.".
while (thePlayer.position.x > thePlayer.position2.x - 60) {
println("x2 =" + thePlayer.position2.x);
thePlayer.position.x = thePlayer.position.x - 1;
println("x =" + thePlayer.position.x);
}
else {
thePlayer.position2.x = thePlayer.position.x;
println("complete");
}
However, when I change it to the sample below (an if statement) it compiles fine and runs through where the only change is substituting 'while' for 'if'.
if (thePlayer.position.x > thePlayer.position2.x - 60) {
println("x2 =" + thePlayer.position2.x);
thePlayer.position.x = thePlayer.position.x - 1;
println("x =" + thePlayer.position.x);
}
else {
thePlayer.position2.x = thePlayer.position.x;
println("complete");
}
I'm really confused by this...
There is no while..else
construct in Java (although Python has one and it's rather nifty).
So, there are two possibilities depending on what you're actually trying to achieve.
First, if you want the else
block to run regardless of the while
block, simply place it afterwards:
while (thePlayer.position.x > thePlayer.position2.x - 60) {
println("x2 =" + thePlayer.position2.x);
thePlayer.position.x = thePlayer.position.x - 1;
println("x =" + thePlayer.position.x);
}
thePlayer.position2.x = thePlayer.position.x;
println("complete");
That will loop until the condition becomes false then execute the remaining code.
On the other hand, if you want the else
block to run only if the while
block didn't run (mimicking Python's while..else
construct), that requires something like a while-within-if
setup:
if (thePlayer.position.x > thePlayer.position2.x - 60) {
while (thePlayer.position.x > thePlayer.position2.x - 60) {
println("x2 =" + thePlayer.position2.x);
thePlayer.position.x = thePlayer.position.x - 1;
println("x =" + thePlayer.position.x);
}
} else {
thePlayer.position2.x = thePlayer.position.x;
println("complete");
}
There, the else
clause only executes if the while
loop ran one or more iterations.
You just need to select the behaviour you want and choose one of the options above.