继续抛出异常,直到找到正确的值

时间:2013-05-12 12:34:25

标签: java

我有以下代码

//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中的索引相关联。现在,我的代码偏向于玩家无法正确进行无效移动的例外,但我想知道如何修改它以便让玩家继续被移动直到他们成为有效的移动。

谢谢! :)

2 个答案:

答案 0 :(得分: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);
}

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

答案 1 :(得分: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...");
    }
}