当前位置:  开发笔记 > 编程语言 > 正文

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

如何解决《继续抛出异常,直到找到正确的值》经验,为你挑选了1个好方法。

我有以下代码

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

谢谢!:)



1> 0909EM..:

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

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

推荐阅读
mobiledu2402851373
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有