Just as the title suggests, I'm trying to create a card game here but am currently having trouble with a discard function in which, I select a card from my hand and discard it into a stack. Each card has a value from 0 to 12. But the problem is that at times I get a NullPointerException
from getting a card with a null
value (which should not exist). I've traced the code and determined that somehow. On top of discarding a normal card, a card with a null
value is discarded as well, given that after testing some code to print the card values of each card in the stack (from top to bottom), the exception appears after the card I've discarded is printed.
Here's the action listener or a button that I click in order to discard a card:
pDiscard1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
if (cardSelected && (dPile == null && sPile == null)) {
game.pdc[0].discard(card);
for (int i = 0; i < game.playerHand.size(); i++) {
if (game.playerHand.get(i) == card) {
game.playerHand.remove(i);
break;
}
}
cardSelected = false;
discarded = true;
display();
} catch (Exception exception) {
System.out.println("The card you have attempted to discard is invalid. You can only discard cards from your hand.");
}
}
});
And down here is the code for the discard:
void discard(SkipBoCard card) {
dPile.push(card);
}
If any other information is needed, please do let me know. Any help regarding this problem would be greatly appreciated.
EDIT: Here's the stack trace:
Exception in thread "main" java.lang.NullPointerException
at SkipBo.SkipBoGUI.display(SkipBoGUI.java:618)
at SkipBo.SkipBoGUI.<init>(SkipBoGUI.java:507)
at SkipBo.SkipBoMain.main(SkipBoMain.java:5)
Line 507 is the call for the display method (which updates the visuals of the GUI), and 618 is a part of an if-statement that changes the text of the cards in the buttons/panels for a card. This is because it doesn't have a try-catch exception handler because I'm try to get to the bottom of why this problem is happening (thus far no luck). This information certainly feels like a dead end, but I hope this can help in any way.