gpt4 book ai didi

java - 根据 Java checkstyle,方法内有太多 return 语句,如何简化代码以符合 2 返回最大值?

转载 作者:行者123 更新时间:2023-12-01 16:47:25 25 4
gpt4 key购买 nike

我的百家乐游戏方法之一是检查庄家是否可以根据玩家的手牌值抽第三张牌。

游戏本身有很多关于庄家是否可以抽牌的条件,这导致我创建了一个包含许多条件语句的方法。我有太多 return 语句,但我不知道如何将其限制为 2。

/**
* Determines if banker draws third card.
* @param playerCard Card object
* @param bankerHand Hand object
* @return boolean if banker gets third card.
*/
public static boolean mustHit(Card playerCard, Hand bankerHand) {
int playerValue = valueOf(playerCard);
int bankerValue = valueOf(bankerHand);
if (playerValue == 2 || playerValue == 3) { //player has 2 or 3
return bankerValue >= 0 && bankerValue <= 4; //banker must have 0-4
} else if (playerValue == 4 || playerValue == 5) { //player has 4 or 5
return bankerValue >= 0 && bankerValue <= 5; //banker must have 0-5
} else if (playerValue == 6 || playerValue == 7) { //player has 6 or 7
return bankerValue >= 0 && bankerValue <= 8; //banker must have 0-8
} else if (playerValue == 8) { //player has 8
return bankerValue >= 0 && bankerValue <= 2; //banker must have 0-2
} else {
return bankerValue >= 0 && bankerValue <= 3;
//if none of the above, banker must have 0-3
}
}

我怎样才能简化这个?

编辑:

已修复,我很可能想得太多了。创建 boolean 变量并为其赋值,而不是返回每个 boolean 值。

/**
* Determines if banker gets third card.
* @param playerCard Card object
* @param bankerHand Hand object
* @return boolean if banker gets third card.
*/
public static boolean mustHit(Card playerCard, Hand bankerHand) {
int playerValue = valueOf(playerCard);
int bankerValue = valueOf(bankerHand);
boolean bankerDraw = false;
if (playerValue == 2 || playerValue == 3) {
bankerDraw = bankerValue >= 0 && bankerValue <= 4;
} else if (playerValue == 4 || playerValue == 5) {
bankerDraw = bankerValue >= 0 && bankerValue <= 5;
} else if (playerValue == 6 || playerValue == 7) {
bankerDraw = bankerValue >= 0 && bankerValue <= 8;
} else if (playerValue == 8) {
bankerDraw = bankerValue >= 0 && bankerValue <= 2;
} else {
bankerDraw = bankerValue >= 0 && bankerValue <= 3;
}
return bankerDraw;
}

最佳答案

您可以尝试使用 Switch 语句

int playerValue = valueOf(playerCard);
int bankerValue = valueOf(bankerHand);
switch(playerValue){
case 2: // Will roll down to the next condition.
case 3: return bankerValue >= 0 && bankerValue <= 4; break;
case 4:
case 5: return bankerValue >= 0 && bankerValue <= 5; break;
case 6:
case 7: return bankerValue >= 0 && bankerValue <= 8; break;
case 8: return bankerValue >= 0 && bankerValue <= 2; break;
default:return bankerValue >= 0 && bankerValue <= 3;

关于java - 根据 Java checkstyle,方法内有太多 return 语句,如何简化代码以符合 2 返回最大值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47441661/

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