簡體   English   中英

在這種情況下如何防止方法兩次運行?

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

這是我的代碼的簡化版本

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..
         */
    }
};

如果用戶設置的distance太大,則觸發“太遠” else語句,並且再次調用該方法,則用戶將獲得新的機會來將distance設置為一個值。

但是問題是: setDistance()結束后,它返回到它的調用點,該點也在setDistance() ,並從那里繼續運行。 這意味着方法setDistance()會運行兩次,因此player變量會切換回其原始狀態。 而且永遠不會是玩家2的回合!

有沒有其他替代方法可以執行此操作,但結果相同。

請嘗試一段時間,而不要調用函數。

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