So once again, we’re thinking logically about an actual game of Blackjack, you’re sitting at the table and you’ve been dealt a “Hand” of cards. What fields and methods might exist for this “Hand” you now possess:
Hopefully you can see these are all logical aspects to a hand. The other important thing to note here is that this “Hand” class needs to be generic enough so that we can use it for the players’ hands but also the dealer’s hand! So let’s create the skeleton for this class (I shouldn’t have to remind you now on how to make a new class):
package source; public class Hand { // MEMBER VARIABLES // ================ private List<Card> cardsInHand = new ArrayList<Card>(); // CONSTRUCTOR // =========== public Hand() { // content here ... } // METHODS // ======= public void addCard(Card cardToAdd) { // content here ... } public String showHand(boolean cardOne) { // content here ... } public int handValue() { // content here ... } public boolean busted() { // content here ... } }
Remember that if we need to import any other libraries to make this work you can press “Ctrl-Shift-O“. While the parameters and return values of these methods may not completely make sense to you just yet, they will hopefully become clearer as we work through how each of these methods needs to function. The only new concept in this snippet of code is the “ArrayList” data type.
ArrayList
An “ArrayList” is very much like the regular arrays we’ve already encountered, the only real difference is that it is dynamic so you can add to and remove from this array during run time. This makes perfect sense in a game like BlackJack because the size of your hand is not always the same. You will see how this gets used as we implement the methods inside this class.