0

我有以下代码

//Querying for move
        int playerMove = currentPlayer.PlayCard(myBoard);

        //Making move
        try {
            playMove(playerMove, currentPlayer);
        } 
        catch (IndexOutOfBoundsException e) {

            System.out.println("Sorry, I don't think you can do that...");

        }

玩家的移动需要与 ArrayList 中的索引相关联。现在,我的代码包含玩家正确做出无效动作的例外,但我想知道如何修改它,以便玩家不断被要求做出动作,直到他们做出有效动作。

谢谢!:)

4

2 回答 2

5

使用 while 循环

while(!IsMoveValid)
{
    int playerMove = currentPlayer.PlayCard(myboard);
    IsMoveValid = CheckMoveValidity(playerMove, myBoard);
}
playMove(playerMove, currentPlayer);

public bool CheckMoveValidity(int move, Board board)
{
    if (move > 0) && (move < board.Length)
    {
        return true;
    } else {
        return false;
    }
    // you could make this helper method shorter by doing
    // return (move > 0) && (move < board.Length);
}

请注意,这不会在逻辑中使用异常:)

于 2013-05-12T12:44:56.883 回答
1

像蛋糕一样简单

while(true){
    //Querying for move
    int playerMove = currentPlayer.PlayCard(myBoard);

    //Making move
    try {
        playMove(playerMove, currentPlayer);
        break; // break the while loop
    } catch (IndexOutOfBoundsException e) {
         System.out.println("Sorry, I don't think you can do that...");
    }
}
于 2013-05-12T12:37:20.663 回答