简体   繁体   English

在这种情况下如何防止方法两次运行?

[英]How to prevent method from running twice in this situation?

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. 如果用户设置的distance太大,则触发“太远” else语句,并且再次调用该方法,则用户将获得新的机会来将distance设置为一个值。

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. 但是问题是: setDistance()结束后,它返回到它的调用点,该点也在setDistance() ,并从那里继续运行。 This means, that the method setDistance() gets ran twice, and so the player variable switches back to its original state. 这意味着方法setDistance()会运行两次,因此player变量会切换回其原始状态。 And it would never be player 2's turn! 而且永远不会是玩家2的回合!

Is there any alternative way to do this but get the same result. 有没有其他替代方法可以执行此操作,但结果相同。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM