You'll want a if
condition that checks the number of card you have inside the deck
(which I assume if an arraylist of Card
) to see if you have anymore cards. Here's an example:
private void DealCard() {
if(!deck.isEmpty())
{
Card c = deck.removeTopCard();
onTable.add(c);
System.out.println(c);
}
else
{
//print something to notify user that the decks is empty, or someother form of handling.
}
}
Another option is to put the if-else conditional inside the removeTopCard()
method, this is more of a programming principle where you have Seperation of Concerns that ensure one method does only one thing, and checking for empty decks might be a job for removeTopCard()
, this is your choice, though.
I would recommend doing error checking rather than catching/throwing exceptions as one should only throw errors when they are truly exceptional, having an empty deck seems like an issue you'll run into fairly often, and not a super special case, so you should handle it. Throwing exceptions are costly, which might not matter to you if you're just a beginner and starting out, (classes I took don't really care) but you want to think about this if you'll be programming in the long run. Here's an SO question with more information on that. You might want to read up more about concepts such as if-else conditionals, handling exceptions and null values and what not for additional knowledge.