【问题标题】:Creating a deck of playing cards using a LinkedList in java在 Java 中使用 LinkedList 创建一副扑克牌
【发布时间】:2023-03-14 08:57:01
【问题描述】:

我不确定我在这里做什么,但我正在尝试使用 Java 中的 LinkedList 集合来创建一副扑克牌。我的逻辑似乎有错误。我在甲板构造函数中不断收到 NullPointerException。

我正在尝试修改使用数组来使用 LikedList 的代码。我错过了什么?

public class Deck {

/** 
 * A LinkedList of cards in the deck, where the top card is the 
 * first index.
 */
private LinkedList<Card> mCards;

/**
 * Number of cards currently in the deck
 */
private int numCards;


/**No args Constructor- if no arguments are used when creating a deck,
 * then we define the game deck to be one deck without shuffling.
 * 
 */
public Deck(){ this(1, false); }

/**Constructor that defines the number of decks (how many sets of 52
 *              cards are in the deck) and whether it should be shuffled.
 * 
 * @param numDecks the number of individual decks in this game deck
 * @param isShuffled whether to shuffle the cards
 */
public Deck(int numDecks, boolean isShuffled){

    this.numCards = numDecks * 52;

    //for each deck
    for (int i = 0; i < numDecks; i++){

        //for each suit
        for(int j = 0; j < 4; j++){

            //for each number
            for(int k = 1; k <= 13; k++){

                //add card to the deck
                this.mCards.add(new Card(Suit.values()[j], k));
            }
        }
    }
    if(isShuffled){
        this.shuffle();
}

public enum Suit {
   Clubs,
   Diamonds,
   Spades,
   Hearts,
}

【问题讨论】:

  • 你没有初始化mCards。此外,编程到接口。 List&lt;...&gt; mCards = new LinkedList&lt;&gt;().
  • 如果我更改为 List,我用什么代替 pop() 来删除第一个元素?
  • remove(0) 或使用Queue 接口,如果您使用的是LinkedList

标签: java collections linked-list


【解决方案1】:

你永远不会初始化mCards

添加(在构造函数的开头):

mCards = new LinkedList<Card>();

【讨论】:

    猜你喜欢
    • 2012-05-07
    • 1970-01-01
    • 1970-01-01
    • 2011-07-09
    • 2019-10-11
    • 2021-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多