This is a simplified version of the code I have:
Thread t = new Thread() {
Scanner user = new Scanner(System.in);
public void run() {
setDistance();
}
void setDistance() {
System.out.print("Set distance.");
int distance = user.nextInt();
if (distance < ableJump) {
jump();
} else { // if you are too weak to jump that far
System.out.print("Too far!");
setDistance();
}
// after that:
if (player == 1) {
player = 2; // sets to 2 if it was player 1's turn
} else if (player == 2) {
player = 1; // sets to 1 if it was player 2's turn
}
System.out.printf("Player %d's turn", player);
/* now a method runs the threads again
* and the cycle continues..
*/
}
};
If distance
the user set is too big, and so triggers the "too far" else
statement and the method gets called again, the user gets a new chance to set distance
to a value.
But the problem is: after setDistance()
has ended, it goes back to the point it was called at, which is also in setDistance()
, and continues running from there. This means, that the method setDistance()
gets ran twice, and so the player
variable switches back to its original state. And it would never be player 2's turn!
Is there any alternative way to do this but get the same result.