我有以下代码

//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中的索引相关联。现在,我的代码隐藏了一个玩家正确做出无效举动的例外,但是我想知道如何修改它,以便不断要求玩家做出举动,直到他们做出有效举动为止。

谢谢! :)

最佳答案

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


注意,这在逻辑上不使用异常:)

关于java - 不断抛出异常,直到找到正确的值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16507394/

10-09 05:22