Reputation: 2852
I am trying to build a simple card game as a personal exercise. I have a collection Cards
that should contain my deck. To initialize it, I want to pass it a map of what the deck should look like - an integer array (1 to n, 1 to 2) with (n, 1) containing a card type which is resolved within the card class, and (n, 2) containing the number of cards that type I want in the deck. I'm having difficulties with a NullPointer exception, however. Here is my Cards
class:
import java.util.LinkedList;
public class Cards{
private LinkedList<Card> CardDeck;
...
public boolean MakeDeck(int[][] DeckMap){
/*feed the function a 2D int array (0 to n, 0 to 1)
@Param - DeckMap[][] - [n][0] to contain card type
[n][1] to contain DupeCount*/
//search the array for duplicates
for (int i = 0; i < DeckMap.length; i++){
int hold = DeckMap[i][0];
DeckMap[i][0] = -10;
for (int j = 0; j< DeckMap.length; j++){
if (DeckMap[j][0] == hold){
DeckMap[i][0] = hold;
return false;
}
}
DeckMap[i][0] = hold;
}
//Add the cards
// tried variations on this: CardDeck = new LinkedList<Card>;
for (int i = 0; i< DeckMap.length; i++){
Card cC = new Card();
cC.initializeCard(DeckMap[i][0], DeckMap[i][1]);
CardDeck.addLast(cC);
}
return true;
}
}
The NullPointer error occurs at the cC.addLast
line - since I have initialized the Card
class, the Null Pointer should refer to the CardDeck
LinkedList I want to add the Card
to, I think. But I can't work out how to initialize the list. Or is the .initializeCard
call the problem (code below)? Thanks in advance for your help and apologies if I've missed something obvious.
Error:
java.lang.NullPointerException at towergame.Cards.MakeDeck(Cards.java:75)
public class Card {
private static String cName;
private static int cDuplicateCount;
public static cEffect myEffects;
public final void initializeCard(int inEffect, int DupeCount){
myEffects = new cEffect();
myEffects.setEffect(inEffect);
cName = myEffects.getCardType();
cDuplicateCount = DupeCount;
}
...
}
Upvotes: 0
Views: 4334
Reputation: 3456
Instead of this private LinkedList<Card> CardDeck;
use this private LinkedList<Card> CardDeck = new LinkedList<Card>();
it is throwing NPE because cardDeck
has not been initialized.
Upvotes: 2