gpt4 book ai didi

java - 牌手: Total value (Java)

转载 作者:太空宇宙 更新时间:2023-11-04 08:30:11 25 4
gpt4 key购买 nike

我目前正在开发一手牌类,该类使用枚举,需要我添加以下方法:

将牌添加到手牌

计算当前手中所有牌的总值(value)(因此,如果手中有 3 个 10,则总值(value)将为 30)

然而,问题是我无法找出如何在手类中实现该方法的同时将所有总数相加(正如任务要求我们这样做)。

任何帮助将不胜感激

这是我的 Suit 枚举的代码

public enum Suit 
{ HEARTS, CLUBS, DIAMONDS, SPADES; }

这是我的 Rank 枚举的代码。这个枚举添加了一些方法,包括 getValue 方法

public enum Rank {   
ONE(1),TWO(2),THREE(3),FOUR(4),FIVE(5), SIX (6), SEVEN(7), EIGHT(8), NINE(9), TEN(10), KING(10), QUEEN(10),
JACK(10);

private final int cardValue;

private Rank ( int nDays) {
cardValue = nDays;
}

public int getValue() {
return cardValue;
}
}

这是 Card 类,它使用 Rank 和 Suit 枚举来打印详细信息(请原谅困惑)

 public class Card {
private Rank rank;
private Suit suit;

public Card (Rank theRank) {
this(theRank,Suit.HEARTS);
}

public Card (Rank theRank, Suit theSuit) {
rank = theRank;
suit = theSuit;
}

public Rank getRank( ) { return rank; }
public Suit getSuit ( ) { return suit; }

public String toString ( ) { return ( rank + " of " + suit +"\n Value of card = " + rank.getValue() ); }

}

这是需要addCard 方法和totalValue 方法的Hand 类。我已经完成了addCard方法,现在需要执行totalValue方法)

 public class Hand {
private Card theCards[ ];
private Rank rank;
private int numCards; private int totalValue;
private static final int max = 5;

public Hand ( )
{
theCards = new Card [max];
numCards = 0;
}

public void addCard( Card aCard )
{
if (numCards < max)
theCards[numCards++] = aCard;
else
{
System.out.println("Cannot add any more cards as hand is full");
}
}

public void totalValue ()
{
int handValue = 0;


for(Card C: theCards)
{
//get the rank values to appear then print them off
//Add up all values of cards and display the total
totalValue = handValue + C.getValue(); //This was just a test to see if calling up the value of card C would work

}
System.out.println("The total value of all the cards is: " + totalValue);
}


public String toString ( )
{
String s = "";
for (int i = 0; i < numCards; ++i) { s += "\n" + theCards[i];
}
return s;
}

就实现而言,它只是创建卡片对象并将它们添加到 Hand 对象的情况,所以我认为我不需要在这里发布它。感谢任何可以帮助我解决问题的人。

最佳答案

Card 没有 getValue() 方法,但 Rank 有。因此,通过其 getRank() 方法获取卡牌的排名,然后对返回的排名调用 getValue()

关于java - 牌手: Total value (Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7698042/

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