二十一点游戏 - Java 的难点 - 超类

问题描述

我正在创建一个 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 + ")");
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...