← Back to Week 5
Workbook 4a Module 5 — Exercise 1
Blackjack
Build a 2-player Blackjack game from three cooperating classes — Card, Hand, and Deck | Workbook p.92
The Exercise
Create a Maven project called blackjack. You'll write three cooperating classes — Card, Hand, and Deck — plus a main class that runs the game.
Prompt the user for each player's name, build a deck, shuffle it, and deal 2 cards to each player's hand. Display each hand and its total. Whichever player is closest to 21 without going over wins.
Example Run
Enter player 1 name: Alice
Enter player 2 name: Bob
Alice's hand:
Cards in Hand:
10 of Hearts
9 of Spades
Bob's hand:
Cards in Hand:
K of Diamonds
5 of Clubs
Alice wins!
Class Wiring (Review)
Each class has its own job. The relationships are has-a: a Hand has Cards, a Deck has Cards. Main orchestrates the game but doesn't do card work itself.
Card
A single playing card. Knows its suit (Hearts/Diamonds/Clubs/Spades), its value (2-10, J, Q, K, A), and whether it's face up. Computes its own point value.
Hand
One player's collection of cards. Accepts a card via deal(card), computes the running total, reports its size.
has-a → Card (many)
Deck
A full pack of 52 cards. Constructor builds them. Knows how to shuffle() and deal() the next card off the top.
has-a → Card (52)
main
Pure orchestration — reads names, asks Deck to shuffle, hands two cards to each Hand, asks each Hand for its total, prints the winner. Does no card math itself.
Scoring Rules
Number Cards
2 - 10
Face value
Face Cards
J Q K
10 points each
Bonus rule: If counting an Ace as 11 would push the hand over 21, count it as 1 instead. This logic belongs inside Hand.getValue(), not in main.
Optional Bonus
Once the basic 2-player game works, layer on:
-
N players. Ask how many players up front, then loop to read that many names and create that many Hands.
-
Hit / Stay. After the initial deal, give each player a turn loop — choose Hit (take another card) or Stay (lock in the total).
-
Smart Aces. Implement the "11 or 1" Ace rule above — only when 11 would bust, drop it to 1.
Flow
1. New Maven project
name: blackjack
→
2. Card.java
suit, value, isFaceUp + flip(), getPointValue()
3. Hand.java
ArrayList<Card> + deal(), getValue(), getSize()
→
4. Deck.java
build 52 cards, shuffle(), deal(), getSize()
5. Wire up main
prompt names, shuffle, deal 2 to each Hand
→
6. Compare + declare winner
7. Bonus: hit/stay loop + ace-as-1 logic
Each class has its own job. Card knows its suit/value/face-up state. Hand stores cards and computes total. Deck builds and deals. main only orchestrates — if you find yourself summing card values inside main, that logic belongs in Hand.
Workbook 4a Module 5, Exercise 1, p.92 — Blackjack