[英]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.