I do not know why the initialization of currentCard
is needed there (where I commented in my code).
Is that statement really needed in this code?
public class Card {
private String face;
private String suit;
public Card( String cardFace, String cardSuit )
{
face = cardFace;
suit = cardSuit;
}
public String toString()
{
return face + " of " + suit;
}
}
===============================================================
import java.util.Random;
public class DeckOfCards
{
private Card[] deck;
private int currentCard;
private static final int NUMBER_OF_CARDS = 52;
private static final Random randomNumbers = new Random();
public DeckOfCards()
{
String[] faces = {"Ace", "Deuce", "Three", "Four",
"Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack",
"Queen", "King" };
String[] suits = {"Hearts", "Diamonds", "Clubs", "Spades"};
deck = new Card[NUMBER_OF_CARDS];
currentCard = 0;
for( int count = 0; count < deck.length; count++)
deck[ count ] =
new Card( faces[ count % 13 ], suits[ count / 13 ] );
}
public void shuffle()
{
currentCard = 0; // I do not know why initialization is needed
for( int first = 0; first < deck.length; first++ )
{
int second = randomNumbers.nextInt( NUMBER_OF_CARDS );
Card temp = deck[ first ];
deck[ first ] = deck[ second ];
deck[ second ] = temp;
}
}
public Card dealCard()
{
if( currentCard < deck.length )
return deck[ currentCard++ ];
else
return null;
}
}
public class DeckOfCardsTest
{
public static void main( String[] args )
{
DeckOfCards myDeckOfCards = new DeckOfCards();
myDeckOfCards.shuffle();
for( int i = 1; i <= 52; i++)
{
System.out.printf("%-19s", myDeckOfCards.dealCard() );
if( i % 4 ==0 )
System.out.println();
}
}
}
currentCard
says which card to deal next (seedealCard()
method)shuffle()
does two things: 1) It shuffles the deck, and 2) resets thecurrentCard
so that the next card to deal is card 0.(The
currentCard = 0
is not necessary for the shuffling itself!)