I’m trying to create a simple card game where the user faces against a computer (which is a class in my method that takes its turn automatically after the user), but I’m encountering a nullPointerException exception that doesn’t let me get past the starting display of the rules. I’m not sure what is wrong, as I have tried everything to fix it, and nothing has worked.
Here is the necessary code from my Deck and Player classes. One of the methods within is throwing the error, but I’m not quite sure which. I suspect the Deck class more though.
One this to note is that the Player class is a subclass of the CardGame class, which runs the game itself. That is why the “shuffledDeck” array list is in there. It’s a Deck object inherited from its superclass.
The Player class:
ArrayList<Card> cardHand = new ArrayList<Card>();
private int numCards = 0;
private boolean hasCards = true;
public Player() {
getCardHand();
}
public void createCardHand() {
int top = 0;
for (int i = 0; i < 5; i++) {
cardHand.add(shuffledDeck.getDeck().get(top));
shuffledDeck.cards.remove(top);
top++;
numCards++;
}
}
The Deck class:
static ArrayList<Card> cards = new ArrayList<Card>();
static ArrayList<Card> pile = new ArrayList<Card>();
private String[] cardNames;
private int[] cardValues;
private int numCardsLeft;
private boolean cardsLeft = true;
public Deck() {
cards = createDeck();
}
public ArrayList<Card> createDeck() {
cardNames = FileReader.toStringArray("cards.txt");
cardValues = FileReader.toIntArray("values.txt");
ArrayList<Card> temp = new ArrayList<Card>();
for (int index = 0; index < cardNames.length; index++) {
temp.add(new Card(cardNames[index], cardValues[index]));
}
return temp;
}
I have tried:
- creating alternative ways to fill both the cardHand and cards array lists
- changing the method createCardHand() to have parameters that include a Deck object to use
The error still persists and prevents me from making any progress. I’m not quite sure which of the two methods is throwing the error, because I’ve tried blocking both out, and the error still happens. But it’s definitely one of them.
Emily Araoju is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.