DeckOfCards Method shuffle
Method shuffle
(lines 30–46) shuffles the Card
s in the deck. The method loops through all 52 Card
s. For each Card
, a number between 0 and 51 is picked randomly to select another Card
, then the current Card
and the randomly selected Card
are swapped in the array. This exchange is performed by the assignments in lines 42–44. The extra variable temp
temporarily stores one of the two Card
objects being swapped. The swap cannot be performed with only the two statements
deck[ first ] = deck[ second ];deck[ second ] = deck[ first ];
If deck[first]
is the "Ace"
of "Spades"
and deck[second]
is the "Queen"
of "Hearts"
, after the first assignment, both array elements contain the "Queen"
of "Hearts" ...
Get Android™ How to Program, Second Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.