【发布时间】: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<...> mCards = new LinkedList<>(). -
如果我更改为 List,我用什么代替 pop() 来删除第一个元素?
-
remove(0)或使用Queue接口,如果您使用的是LinkedList。
标签: java collections linked-list