I am having an error with my BlackJack Java game. The error is:
Exception in thread "main" java.lang.NullPointerException
at com.keegan.game.blackjack.Deck.createDeck(Deck.java:48)
at com.keegan.game.blackjack.Deck.<init>(Deck.java:33)
And I am pretty clueless as to what the problem is in this code. Can anyone help me understand what the error is telling me that is wrong?
Here is the code for Deck.java
:
public class Deck {
private ArrayList<Card> deck = new ArrayList<Card>();
private List<Card> cardUsed = new ArrayList<Card>();
Card c = new Card(null, null, null, 0);
public Deck(int numCards) {
this.createDeck(numCards, 4, null);
}
private void createDeck(int numCards, int numSuits, String[] cardRanks) {
deck = new ArrayList<Card>();
cardUsed = new ArrayList<Card>();
if ((numCards % numSuits) > 0) return;
for (int i=0; i < numSuits; i++) {
for(int j=1; j <= (numCards / numSuits); j++) {
deck.add(new Card(new Suit(i), cardRanks[j-1], cardRanks, j));
}
}
}
public Card dealCard( ) {
Card dealtCard = null;
if (deck.size() == 0){
deck.addAll(cardUsed);
this.shuffle();
cardUsed = new ArrayList<Card>();
}
dealtCard = deck.get(0);
deck.remove(0);
cardUsed.add(dealtCard);
return dealtCard;
}
public void shuffle() {
Collections.shuffle(deck);
}
public ArrayList<Card> getDeck() {
return deck;
}
public void setDeck(ArrayList<Card> deck) {
this.deck = deck;
}
public int getNumUsedCards() {
return cardUsed.size();
}
public List<Card> getCardUsed() {
return cardUsed;
}
public void setCardUsed(List<Card> cardUsed) {
this.cardUsed = cardUsed;
}
You're passing a null
array
this.createDeck(numCards, 4, null);
and later accessing it as cardRanks[j-1]
in your statement
deck.add(new Card(new Suit(i), cardRanks[j-1], cardRanks, j));
EDIT :
What you probably need is to create your Deck
as
this.createDeck(numCards, 4);
and adding the Card
as
deck.add(new Card(new Suit(i), j));
since, String[] cardRanks
is already initialized in your Card
class. And, design-wise it's correct because Deck
shouldn't have to know about card ranks. Card
should encapsulate it and maybe implements Comparable as well.