19. The final methods

We have a constructor and four methods to go before our game is complete. Why don’t we start with the constructor.

So you can see we have five fields inside this class. We have an instance of the Deck class called “deck“, we have two instances of the Hand class called “player” and “dealer” and we have two other variables that are basically just used to help us. So the important thing our constructor needs to do is create the deck and hands:

deck = new Deck(52);
player = new Hand();
dealer = new Hand();
keyboard = new BufferedReader(new InputStreamReader(System.in));

You can see I’ve also made an instance of something called…InputStreamReader. Don’t be intimidated by this, it’s simply the way we get what the user types in, you’ll see it in use soon.

One of the important things to note here is that even though the dealer and player are fairly different objects in a game of Blackjack, in our program they are instances of the same class, this implies an adaptable Object-Oriented class, handy!

Now that we’ve constructed the objects needed in our game, let’s turn our attention to the easiest method. When it’s time to deal the cards to the players, what happens? Basically a card is taken from the deck and added to the hand of a player, they receive two such cards and then the dealer gets two cards, in other words:


Bam! Object-Oriented programming FTW! Those lines look simple but are only possible because of well-planned and well-written methods in our other classes.

This method is probably the most important in the whole program. In fact, this is probably one of the first methods that you’d consider when thinking about a project like this. It is meant to mimic the way a game of Blackjack is played and if our other classes are written well enough, the logic will be quite easy to follow, see if you can follow it:

System.out.println("Welcome to Blackjack!");
do {
   System.out.print("Hit/H/h or Stay/S/s: ");
   input = Character.toLowerCase(keyboard.readLine().charAt(0));
   if (input == 'h') {
} while ((!player.busted()) && (input == 'h'));

While some of the Java code might be new and a little confusing you can hopefully see the structure of a game is basically this:

// welcome the player
// shuffle the deck
// deal the initial cards
// repeat
//    show the player's hand and ask what they want to do
//    if they want to hit
//       give them another card
// until the player busts or they want to stop getting cards
// let the dealer have their turn
// work out the results of the game and show them

Okay, that leaves us with two methods to finish…

Leave a Comment

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>