Build a 52-card deck from Suit and Rank enums and a Card record, then deal a fixed hand (cards 0, 13, 26, 39 and 51), print it and its total points (A=11, face=10).
Solution
Main.java
import java.util.ArrayList;
import java.util.List;
enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES }
enum Rank {
TWO(2), THREE(3), FOUR(4), FIVE(5), SIX(6), SEVEN(7), EIGHT(8), NINE(9), TEN(10), JACK(10), QUEEN(10), KING(10), ACE(11);
final int points;
Rank(int p) { points = p; }
}
record Card(Rank rank, Suit suit) {
@Override public String toString() { return rank + " of " + suit; }
}
public class Main {
public static void main(String[] args) {
List<Card> deck = new ArrayList<>();
for (Suit s : Suit.values()) for (Rank r : Rank.values()) deck.add(new Card(r, s));
List<Card> hand = new ArrayList<>();
for (int i : new int[]{0, 13, 26, 39, 51}) hand.add(deck.get(i));
int points = hand.stream().mapToInt(c -> c.rank().points).sum();
System.out.println(deck.size() + " cards, hand: " + hand);
System.out.println("points " + points + ", aces " + hand.stream().filter(c -> c.rank() == Rank.ACE).count());
}
}
Output Verified by compiling and running
52 cards, hand: [TWO of CLUBS, TWO of DIAMONDS, TWO of HEARTS, TWO of SPADES, ACE of SPADES]
points 19, aces 1
Nested loops over values() build every combination; the record overrides toString for readable output.
More Records, Enums and Sealed Classes practice questions
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!