Java Reference
In-Depth Information
TRY IT OUT: Dealing Cards
You can use a Stack<> object along with another useful method from the Collections class to simulate
dealing cards from a card deck. You need a way of representing a card's suit and face value or rank. An
enum type works well because it has a fixed set of constant values. Here's how you can define the suits:
public enum Suit {
CLUBS, DIAMONDS, HEARTS, SPADES
}
Directory "TryDeal"
The sequence in which the suits are defined here determines their sort order, so CLUBS is the lowest and
SPADES is the highest. Save this source file as Suit.java in a new directory for the files for this example.
You can define the possible card face values just as easily:
public enum Rank {
TWO, THREE, FOUR, FIVE, SIX, SEVEN,
EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE
}
Directory "TryDeal"
TWO is the lowest card face value, and ACE is the highest. You can save this as Rank.java . You're now
ready to develop the class that represents cards. Here's an initial outline:
public class Card {
public Card(Rank rank, Suit suit) {
this.rank = rank;
this.suit = suit;
}
private Suit suit;
private Rank rank;
}
Directory "TryDeal"
Search WWH ::




Custom Search