Java Reference
In-Depth Information
in order by suit and face. Line 10 invokes
myDeckOfCards
's
shuffle
method to rearrange
the
Card
objects. Lines 13-20 deal all 52
Card
s and print them in four columns of 13
Card
s each. Line 16 deals one
Card
object by invoking
myDeckOfCards
's
dealCard
meth-
od, then displays the
Card
left justified in a field of 19 characters. When a
Card
is output
as a
String
, the
Card
's
toString
method (lines 17-20 of Fig. 7.9) is implicitly invoked.
Lines 18-19 start a new line after every four
Card
s.
1
// Fig. 7.11: DeckOfCardsTest.java
2
// Card shuffling and dealing.
3
4
public
class DeckOfCardsTest
5
{
6
// execute application
7
public static void
main(String[] args)
8
{
9
DeckOfCards myDeckOfCards =
new
DeckOfCards();
10
myDeckOfCards.shuffle();
// place Cards in random order
11
12
// print all 52 Cards in the order in which they are dealt
13
for
(
int
i =
1
; i <=
52
; i++)
14
{
15
// deal and display a Card
16
System.out.printf(
"%-19s"
, myDeckOfCards.dealCard());
17
18
if
(i %
4
==
0
)
// output a newline after every fourth card
19
System.out.println();
20
}
21
}
22
}
// end class DeckOfCardsTest
Six of Spades Eight of Spades Six of Clubs Nine of Hearts
Queen of Hearts Seven of Clubs Nine of Spades King of Hearts
Three of Diamonds Deuce of Clubs Ace of Hearts Ten of Spades
Four of Spades Ace of Clubs Seven of Diamonds Four of Hearts
Three of Clubs Deuce of Hearts Five of Spades Jack of Diamonds
King of Clubs Ten of Hearts Three of Hearts Six of Diamonds
Queen of Clubs Eight of Diamonds Deuce of Diamonds Ten of Diamonds
Three of Spades King of Diamonds Nine of Clubs Six of Hearts
Ace of Spades Four of Diamonds Seven of Hearts Eight of Clubs
Deuce of Spades Eight of Hearts Five of Hearts Queen of Spades
Jack of Hearts Seven of Spades Four of Clubs Nine of Diamonds
Ace of Diamonds Queen of Diamonds Five of Clubs King of Spades
Five of Diamonds Ten of Clubs Jack of Spades Jack of Clubs
Fig. 7.11
|
Card shuffling and dealing.
Preventing
NullPointerException
s
In Fig. 7.10, we created a
deck
array of 52
Card
references—each element of every refer-
ence-type array created with new is default initialized to
null
. Reference-type variables
which are fields of a class are also initialized to
null
by default. A
NullPointerException
occurs when you try to call a method on a
null
reference. In industrial-strength code, en-
suring that references are not
null
before you use them to call methods prevents
Null-
PointerException
s.