Please help me with the TODO statements in the program package pkgCore; import j
ID: 3724272 • Letter: P
Question
Please help me with the TODO statements in the program
package pkgCore;
import java.util.ArrayList;
public class Deck {
// TODO: Add 'cards' attribute that is an ArrayList of Card
private ArrayList<Card> cards = new ArrayList<Card>();
public Deck(ArrayList<Card> cards) {
super();
this.cards = cards;
}
// TODO: Add a contructor that passes in the number of decks, and then populates
// ArrayList<Card> with cards (depending on number of decks).
// Example: Deck(1) will build one 52-card deck. There are 52 different cards
// 2 clubs, 3 clubs... Ace clubs, 2 hearts, 3 hearts... Ace hearts, etc
// Deck(2) will create an array of 104 cards.
// TODO: Add a draw() method that will take a card from the deck and
// return it to the caller
}
Explanation / Answer
import java.util.*;
public class Deck
{
public static final int HEARTS = 0;
public static final int DIAMONDS = 1;
public static final int SPADES = 2;
public static final int CLUBS = 3;
public static final int JACK = 11;
public static final int QUEEN = 12;
public static final int KING = 13;
public static final int ACE = 14;
private ArrayList<Card> deck;
public Deck(ArrayList<Card> cards) {
super();
this.deck = cards;
}
//This creates a deck. A deck starts as a list of 52 cards.
//We loop through each suit and rank and construct a card and
//add it to the deck.
public Deck()
{
deck = new ArrayList<Card>();
for(int rank = 2; rank <= ACE; rank++)
{
for(int suit = HEARTS; suit <= CLUBS; suit++)
{
Card card = new Card(rank, suit);
deck.add(card);
}
}
shuffle();//Shuffling the cards for the first time.
}
//This getter method returns the ArrayList of cards.
public ArrayList getCards()
{
return deck;
}
//This deals the first card from the deck by removing it.
public Card draw()
{
return deck.remove(0);
}
//This shuffles the deck by making 52 swaps of cards positions.
public void shuffle()
{
for(int i = 0; i < deck.size(); i++)
{
Random r = new Random();
int randomIndex = r.nextInt(52);
Card>
Card two = deck.get(randomIndex);
deck.set(i,two);
deck.set(randomIndex,one);
}
}
}