gpt4 book ai didi

java - 不断抛出异常,直到找到正确的值

转载 作者:行者123 更新时间:2023-12-01 08:12:07 26 4
gpt4 key购买 nike

我有以下代码

//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 中的索引相关联。现在,我的代码捕获了玩家正确做出无效 Action 的异常,但我想知道如何修改它,以便不断要求玩家做出 Action ,直到他们做出有效的 Action 。

谢谢! :)

最佳答案

使用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com