问题描述
我正在创建一个 21 点程序,但被卡住了,如果有任何可用的帮助,我将不胜感激。 我有一个 Player 类和一个 Card 类。
以下函数 (getHandValue) 用于计算玩家手牌的总价值。
/*getHandValue - accessor that computes the total value of the
player's current hand
*/
public int getHandValue(Card[] hand){
int total = 0;
for (Card card : hand){
String rank = card.getRankName();
total += card.getValue();
if (rank.equals("Ace") && total < 11){
total += 10;
}
}
return total;
}
printHand 方法旨在使用 getHandValue 打印玩家手牌的内容和玩家手牌的价值。
/* ISSUES
* printHand - accessor that prints the current contents
of player's hand followed by value of player's hand
*/
public static void printHand(Card hand[]){
int value = hand.getHandValue();
for(int i = 0; i<hand.length; i++){
System.out.println(hand[i] + " ");
}
System.out.print("(value = " + value + ")");
}
我一直在 printHand 方法中收到“无法在数组类型 Card[] 上调用 getHandValue()”的错误消息。
我不确定我做错了什么,我确定是因为我构建这些类的方式,但我什至不知道从哪里开始
感谢您的时间
解决方法
您正在使用一个数组,并且您需要期望它作为一个数组工作,您需要将 hand.getHandValue();
移到循环内并让值留在外面。
像这样:
public static void printHand(Card hand[]){
int value = 0;
for(int i = 0; i<hand.length; i++){
value += hand[i].getHandValue();
System.out.println(hand[i] + " ");
}
System.out.print("(value = " + value + ")");
}