I’m getting NullPointerException because I try to check some value from an object that has yet to be initialized and value is still null value. The reason for this is that I’m waiting to initialize object only when necessary, when is not necessary I figure I don’t need to waste more memory space.
I’m getting this exception because player2.getHandTotal() has not been initialized yet so there is no method to pull value from. Now, how should I formulate my while loop to not throw this exception when I check for a value? I tried to throw (player2 != null && dealer.getHandTotal() <= player2.getHandTotal()) and hoped to short circuit checking it but that doesn’t work…
The player2 meant to be a hand which will be used when cards are split into 2 hands for the same player. If there are no requirements for split such as no 2 cards or cards ranks are not the same then I don’t need player2 object to be initialized.
I really don’t want to double my code! The reason for this is that I would have to double A LOT of code! And I would be better off initializing player2 object even when not necessary!
How to fix this?
while(dealer.getHandTotal() <= 15 &&
(dealer.getHandTotal() <= player.getHandTotal() ||
dealer.getHandTotal() <= player2.getHandTotal()))
{
deck = drawFromDeck(deck, dealer);
}
So your class structure is not correct: a Player (and the Dealer) should have one or more Hands and the condition should something like:
Then in the future when you want to add extra players you just need to add an extra loop in the getMaximumHandTotal() over all the players.