开发者

Return the size of the array of Cards

writing a Deck class that represents a deck of cards. It starts off with 52 cards, but as cards are dealt from the deck, the number of cards becomes smaller. this class has one private instance variable that stores the Cards that are currently in the Deck. it is private Card[] cards;

i need to write a method that returns the size of the array of Cards. (It starts off equal to 52, but becomes smaller as cards are dealt from the deck.)

would it be something like this?

public int getNumCards() 
{
    int getNumCards = 52;

    for(int i = getNumCards; i > 0; --i)
        getNumCards = i;

    return getN开发者_如何学CumCards;


}


The size of the array is always 52.

And your code does nothing else than iterating 52 time through the loop.

Assuming that you set the cards that are removed to null, you could use the following code:

public  int getNumCards() 
    {

        int counter = 0;
        for(int i = 0; i < cards.length; i++) {
            if (cards[i] != null) {
                counter++;
            }
        }
        return counter;
    }

But the better solution would be to use a list for your cards:

private ArrayList<Card> cards = new ArrayList<Card>();

Then you can easily calculate the number of cards:

public int getNumCards() 
    {
        return cards.size();
    }


You can do this with one line of code.

public int get numCards() {
    for (int count = 0; cards[count] != null; count++);
    return count;
}


No, your code does not make any sense. It will always return the same answer.

This is not surprising when you realise that your code does not even look at the array.

Try to Google it.


If you indeed need to use arrays (not lists or sets or anything else), then first you need to decide on a way to remove cards from the deck. After you decided on that, you can proceed to "remaining cards in the deck" calculation.

Given the array, here are your possibilities in removing cards from it:

  1. Assign null to one of the array elements. To find the size - you loop through the array and count all elements that are not null.
  2. Create new array which is smaller and does not contain the removed card. Then assign the new array to old array's variable. In this case, length will be simple cards.length.
  3. Add some property to hold 'dealt' status of each card. For example card.isDealt=true. In this case you loop through the array and count all cards that have the given flag equal to false.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜