Java Reference
In-Depth Information
An overloaded version of the
shuffle()
method enables you to supply an object of type
Random
as the
second argument, which is used for selecting elements at random while shuffling.
The final piece of the example is a class that defines
main()
:
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);
}
}
Directory "TryDeal"
I got the following output:
My hand is:
THREE of CLUBS, TWO of DIAMONDS, SEVEN of DIAMONDS, FOUR of SPADES,
JACK of SPADES
Your hand is:
FOUR of CLUBS, FIVE of CLUBS, TWO of HEARTS, ACE of HEARTS, THREE of
SPADES
You will almost certainly get something different.
How It Works
Your code for
main()
first creates a
CardDeck
object and calls its
shuffle()
method to randomize the
sequence of
Card
objects. You then create two
Hand
objects of five cards with the following statements:
Hand myHand = deck.dealHand(5).sort();
Hand yourHand = deck.dealHand(5).sort();
The
dealHand()
method returns a
Hand
object that you use to call its
sort()
method. Because the
sort()
method returns a reference to the
Hand
object after sorting, you are able to call it in a single
statement like this. The
Hand
object that the
sort()
method returns is stored in the local variable, either
myHand
or
yourHand
as the case may be. The output statements just display the hands that were dealt.
A
Stack<>
object is particularly well suited to dealing cards because you want to remove each card from
the deck as it is dealt, and this is done automatically by the
pop()
method that retrieves an object. When
you need to go through all the objects in a stack without removing them, you can use a collection-based
for
loop, just as you did for the
Vector<Card>
object in the
toString()
method in the
Hand
class. Of