1

在我正在做的一个程序上需要帮助。所以我分配了我的数组,例如:

hand = new PlayingCard[5]; //5 Cards in a hand

hand[0]我为and设置了信息hand[1]

hand[0] = deck.dealACard(); 
hand[1] = newDeck.dealACard();

我的问题是,当我试图弄清楚目前有多少张牌[]时,我得到的是“5”而不是“2”。

numCards = hand.length;

我现在需要做什么才能让 numCards 等于“2”?

4

4 回答 4

4

那么你可以很容易地使用:

public static int countNonNullElements(Object[] array) {
    int count = 0;
    for (int i = 0; i < array.length; i++) {
        if (array[i] != null) {
            count++;
        }
    }
    return count;
}

但是,通常最好使用 aList<E>代替(例如ArrayList<E>)来表示具有不同大小的集合。

于 2013-04-22T12:46:05.157 回答
1

你可以循环遍历:

int count = 0
for (PlayingCard c : hand) {
    if (c != null) count ++
}
//count is now how many cards there are
于 2013-04-22T12:46:14.750 回答
0

您可以实现一个方法来迭代整个数组以查看索引中是否有元素,或者您可以保留一个带有数字的局部变量,并通过添加和删除来控制它。

如果可能的话,我更喜欢第二个。它以恒定时间为您提供 1 个局部变量的价格的答案,而不是线性时间,就像第一个解决方案一样

于 2013-04-22T12:46:38.737 回答
0

您正在创建一个数组PlayingCard其一旦初始化将具有固定大小,即5在您的情况下..

您可以使用List

List<PlayingCard> playingCardList=new ArrayList();
playingCardList.add(new PlayingCard());
playingCardList.add(new PlayingCard());

大小为playingCardList2

于 2013-04-22T12:47:02.050 回答