So with the skeleton in place, let’s now implement all these methods. We’ll start with one of the easiest ones:
addCard()
The “addCard” method simply needs to take the “Card” object that’s been passed in and put it onto our “ArrayList” object, i.e.
cardsInHand.add(cardToAdd);
And that’s it! The “add” method of the “ArrayList” class simply puts an item onto the end of our dynamic array. Nice and simple! Next up let’s build the “handValue” method.
handValue()
This method doesn’t involve anything too new, it simply requires some problem solving. What we need to do is go through each of the cards in the hand and find the best total, remember that an ace can count as 1 or 11 in Blackjack:
int handTotal = 0; int aceCount = 0; for (int i = 0; i < cardsInHand.size(); ++i) { if (cardsInHand.get(i).cardRank <= 10) { handTotal = handTotal + cardsInHand.get(i).cardRank; } else if (cardsInHand.get(i).cardRank <= 13) { handTotal = handTotal + 10; } else { handTotal = handTotal + 11; aceCount = aceCount + 1; } } while ((handTotal > 21) && (aceCount > 0)) { handTotal = handTotal - 10; aceCount = aceCount - 1; } return handTotal;
You can see we’ve used two new methods in here that are part of the “ArrayList” class, “get” and “size“. Apart from this, the logic is fairly self-explanatory.
An important point to note in this implementation is that we are attempting to reference the “cardRank” field of the Card class, but because we had set this to private, Eclipse is going to report an error. There are two ways to fix this:
- Change the visibility of “cardRank“: This would allow the user of the “Card” class to see a field that you may not want them to see though? In our case, we’ve made that field “final” anyway so it doesn’t overly matter but it’s not the best solution.
- Create a “getter” method: This is the preferred way of accessing field information, you simply create a new public method inside the “Card” class that gives you back the value of “cardRank“.
So we’ll fix this error by using the second technique. This means we need to make two changes to our code, firstly let’s add a new “getter” method to our “Card” class:
public int get_cardRank() { return cardRank; }
The second change involves altering the code we originally tried using for the “handValue” method…we need to change any reference to “cardRank” into “get_cardRank()” instead, the three changes should look like this:
if (cardsInHand.get(i).get_cardRank() <= 10) { handTotal = handTotal + cardsInHand.get(i).get_cardRank(); } else if (cardsInHand.get(i).get_cardRank() <= 13) {
Hopefully now you’re starting to get a sense of how Object-Oriented programming works…protect your data and create standalone classes wherever possible!
Okay, this lesson has gotten pretty big, let’s finish the “Hand” class in the next one!