1

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.

Zeroten
  • 13
  • 3
  • 4
    Use a loop instead of "recursion"? Why are you calling the same method again just to get a different input? – UnholySheep Jul 11 '18 at 12:56
  • Just put a `return;` after the recursive call to `setDistance();` – marstran Jul 11 '18 at 12:57
  • `return;` at the end of the `else` – jhamon Jul 11 '18 at 12:58
  • Related: [Asking user to enter the input again after he gives a wrong value for the Input. InputMismatchException?](https://stackoverflow.com/questions/25002802/asking-user-to-enter-the-input-again-after-he-gives-a-wrong-value-for-the-input) There are bound to be many more. Please search. – Ole V.V. Jul 11 '18 at 13:01
  • Man, you're a genius, thanks! – Zeroten Jul 11 '18 at 13:02

1 Answers1

2

Try to do it with a while instead of recalling your function.

void setDistance() {
    int distance;
    while (true) {
        System.out.print("Set distance.");
        distance = user.nextInt();
        if (distance < ableJump) {
            break;
        }
        System.out.print("Too far!");
    }
    jump(); 
    // after that:
    player = 3 - player;
    System.out.printf("Player %d's turn", player);
}
Roee Gavirel
  • 18,955
  • 12
  • 67
  • 94