gpt4 book ai didi

java - 方法调用的 Stackoverflow

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

我真的希望我能在 SO 上讽刺性地解决这样的问题。无论如何,我正在使用 java 制作一个二十一点程序,并且在尝试处理 ACE 的使用方式时遇到了错误。对于那些不了解游戏的人来说,ACE 可以算作 11 或 1,并且为了这个程序,我将其自动算作 11,除非您失败(您的分数超过 21)。我的问题是我有 3 种方法:

public int getPlayerScore() {

int pScore = 0;

for (int i = 0; i < playerHand.size(); i++) {
pScore = pScore + getCardScore(playerHand.get(i), "P");
}

return pScore;


public int getCardScore(Card c, String s) {

int cardScore = 0;
// gets the score of the card based on value
switch (c.getValue()) {
case TWO:
cardScore = 2;
break;
case THREE:
cardScore = 3;
break;
case FOUR:
cardScore = 4;
break;
case FIVE:
cardScore = 5;
break;
case SIX:
cardScore = 6;
break;
case SEVEN:
cardScore = 7;
break;
case EIGHT:
cardScore = 8;
break;
case NINE:
cardScore = 9;
break;
case TEN:
cardScore = 10;
break;
case JACK:
cardScore = 10;
break;
case QUEEN:
cardScore = 10;
break;
case KING:
cardScore = 10;
break;
case ACE:
cardScore = getAceScore(s);
break;
}

return cardScore;
}


public int getAceScore(String s) {
int aceScore = 0;
int tempScore = 0;
if(s.equals("P")){
tempScore = getPlayerScore() + 11;
}
else{
tempScore = getDealerScore() + 11;
}
// if an ace as 11 doesn't bust player
if (tempScore <= 21) {
aceScore = 11;
}
// if an ace as 11 busts player
else if (tempScore >= 21) {
aceScore = 1;
}

return aceScore;
}

我知道为什么会出现堆栈溢出错误,我的getAceScore()正在调用getPlayerScore()依次调用 getAceScore()等等。我尝试拥有 int playerScore必要时更新的全局变量,问题是它会在不应该更新时更新并更改 ACE 分数。例如,如果我的 ACE、NINE 得分为 20,那么它会说我的得分是 10,因为它会说如果 ACE 是 11,那么我的得分将为 31。我正在考虑与 getCardScore 分开制作另一种方法。 ,从该方法中删除 ACE 情况,然后不断检查玩家手中是否有 ACE,然后调用 getAceScore 。但这似乎太多了。谁能提供一个更简单的解决方案?

最佳答案

摆脱递归,你就会没事的。 getAceScore 方法可以将没有 Ace 的玩家分数作为参数。然后它会根据 11 是否会打败他而返回 1 或 11

public int getAceScore( int playerScoreWithoutAce ) {
int aceScore = ( playerScoreWithoutAce + 11 <= 21 ) ? 11 : 1;
return aceScore;
}

我想无论如何我都会以不同的方式对整个解决方案进行建模。您应该只拥有 Player 对象,并避免整个“如果庄家/如果玩家”的区别。 Player 对象在某个时刻有一个方法来计算他手牌的得分。这就是决定 Ace 值(value)的方法

public int handScore( List<Card> cards ) {
int handScore = 0;
// This assumes cards come in sorted with Ace last
for( Card card : cards ) {
int cardValue = ( card == ACE ) ? aceValue( handScore ) ? card.getValue();
handScore += cardValue;
}
return handScore;
}

private int aceValue( int handScore ) {
return ( handScore + 11 <= 21 ) ? 11 : 1;
}

关于java - 方法调用的 Stackoverflow,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22887153/

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