尝试打印桥牌游戏时出现null错误

时间:2015-05-03 06:32:09

标签: java

当我运行main

时,我在此行上收到java null错误
int rank = cards[i].getRank();

int points = cards[i].getPoints();

我只是想在手数组中获取卡片的countHighCardPoints()点值,并将这些点加到一个总和上。 如果我还没有在char suit = cards[i].getSuit();

上获得null,我也会假设我的countDistributionPoints()会起作用

因此,我需要帮助的课程。

public class Hand
{

 //Holds an array of card objects
 private Card [] cards = new Card [13];

/**
 * Constructor takes array of Cards and assigns that parameter to
 * the instance variable
 */
public Hand(Card [] cards)
{
    Card [] hand = cards;
}

/**
 * Looks through each card in hand array and adds its points
 * if the card has any to a sum highPoints
 */
public int countHighCardPoints()
{
    int highPoints = 0;

    for (int i = 0; i < cards.length; i++) {

        int rank = cards[i].getRank();
        int points = cards[i].getPoints();

       highPoints += points;

    }

    return highPoints;
}


public int countDistributionPoints()
{
    int countPoints = 0;

    for (int i = 0; i < cards.length; i++) {
        //char suit = cards[i].getSuit();

        if (cards[i].getSuit() >= 3)
            countPoints = 0;
        else if (cards[i].getSuit() == 2)
            countPoints++;
        else if (cards[i].getSuit() == 1)
            countPoints += 2;
        else if (cards[i].getSuit() == 0)
            countPoints += 3;
    }

    return countPoints;
}

甲板类供参考

public class Deck
{
//Holds an array of card objects
private Card [] cards  = new Card [52];

//Holds number of cards remaining in deck
private int count;


/**
 * Creates a Card [] arrayOfCards which is 13 cards for each player 
 * and will determine number of cards that was dealt with count.
 */
public Card [] dealThirteenCards()
{
    Card [] arrayOfCards = new Card [13];

    for (int i = 0; i <= 12 && count < 52; i++) {
        arrayOfCards[i] = cards[i];
        count++;
    }

    return arrayOfCards;
}

1 个答案:

答案 0 :(得分:2)

还在玩你的代码,但目前我已经在这里找到了一些东西:

1.在你的Hand的构造中,你永远不会将你传入的值赋给它的实例变量卡,这就是为什么每个Hand下面的牌组将是一个空数组。你应该把它改成:

public Hand(Card [] cards) {
    this.cards = cards;
}

2. Deck下的dealThirteenCards行为异常。

for (int i = 0; i <= 13 && count < 52; i++) {
    arrayOfCards[i] = cards[i];
    count++;
}

初始化Deck后,计数将为-1。以上代码将为4名玩家执行4次,每次为每位玩家分配14张牌。 如果正确结束,则计数将为-1 + 4 * 14 = 55,大于52。因此,您的for循环将比预期更早终止。这表明你的第4位玩家将无法获得我认为的最后3张牌。

希望这有帮助。