控制台程序。
public enum Rank {
TWO, THREE, FOUR, FIVE, SIX, SEVEN,
EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE
}
public enum Suit {
CLUBS, DIAMONDS, HEARTS, SPADES
}
public class Card implements Comparable<Card> {
public Card(Rank rank, Suit suit) {
this.rank = rank;
this.suit = suit;
} @Override
public String toString() {
return rank + " of " + suit;
} // Compare two cards
public int compareTo(Card card) {
if(suit.equals(card.suit)) { // First compare suits
if(rank.equals(card.rank)) { // So check face values
return 0; // They are equal
}
return rank.compareTo(card.rank) < 0 ? -1 : 1;
} else { // Suits are different
return suit.compareTo(card.suit) < 0 ? -1 : 1; // Sequence is C<D<H<S
}
} private Suit suit;
private Rank rank;
}
// Class defining a hand of cards
import java.util.Vector;
import java.util.Collections; public class Hand {
// Add a card to the hand
public void add(Card card) {
hand.add(card);
} @Override
public String toString() {
StringBuilder str = new StringBuilder();
boolean first = true;
for(Card card : hand) {
if(first) {
first = false;
} else {
str.append(", ");
}
str.append(card);
}
return str.toString();
} // Sort the hand
public Hand sort() {
Collections.sort(hand);
return this;
} private Vector<Card> hand = new Vector<>(); // Stores a hand of cards
}
import java.util.Stack;
import java.util.Collections; public class CardDeck {
// Create a deck of 52 cards
public CardDeck() {
for(Suit suit : Suit.values())
for(Rank rank : Rank.values())
deck.push(new Card(rank, suit));
} // Deal a hand
public Hand dealHand(int numCards) {
if(deck.size() < numCards) {
System.err.println("Not enough cards left in the deck!");
System.exit(1);
} Hand hand = new Hand();
for(int i = 0; i < numCards; ++i) {
hand.add(deck.pop());
}
return hand;
} // Shuffle the deck
public void shuffle() {
Collections.shuffle(deck);
} private Stack<Card> deck = new Stack<>();
}
洗牌使用Collections类中一个静态的参数化方法shuffle()方法,该方法会打乱实现了List<>接口的任何集合中的内容。
class TryDeal {
public static void main(String[] args) {
CardDeck deck = new CardDeck();
deck.shuffle(); Hand myHand = deck.dealHand(5).sort();
Hand yourHand = deck.dealHand(5).sort();
System.out.println("\nMy hand is:\n" + myHand);
System.out.println("\nYour hand is:\n" + yourHand);
}
}