6. Dealing Cards Write a class named Card, which can be used to represent a card
ID: 3806221 • Letter: 6
Question
6. Dealing Cards Write a class named Card, which can be used to represent a card from a deck of cards. The class should be able to store a card’s suit and face value. A card’s suit can be one of the following: Hearts, Diamonds, Spades, or Clubs. A card’s face value can be Ace, Jack, Queen, King, or a value in the range of two through ten. Next write a Deck class. This class constructor should create a list of 52 Card objects, each representing a valid card in a deck of cards. The class should have a shuffle method that randomly shuffles the Card objects in the list. It should also have a deal method that “deals” a card from the deck. It does this by removing the Card object at the beginning of the list and returning a reference to that object. Next, write CardPlayer class. This class should keep a list of Card objects that have been dealt to it. This represents a hand of cards. A method named getCard should accept a reference to a Card object, which is added to the list. A method named showCards displays the Card objects in the list. Demonstrate these classes in an application that creates a Deck object, shuffles the cards it contains, and deals five cards from the Deck to a CardPlayer object. The CardPlayer should then display its cards.
Explanation / Answer
public class Deck
{
private Card [] deck;
private int numberOfCards;
public Deck()
{
String [] suits = {"SPADES","DIAMONDS","CLUBS","HEARTS"};
for ( int suit = 0; suit <= 3; suit++ )
{
for ( int rank = 1; rank <= 13;rank++ )
{
numberOfCards = 0;
deck [numberOfCards] = new Card(rank,suit);
numberOfCards ++;
}
}
numberOfCards = 52;
}
public String toString()
{
String deckString = "New deck created ";
for (int cards =0; cards <52; cards++)
{
deckString = deckString + deck[cards] + " ";
}
System.out.println(deckString);
return deckString;
}
}
——————————————
public class Card
{
private String rank;
private String suit;
public Card(int rank, int suit)
{
if(suit == 0)
{
this.suit = "Spades";
}
else if(suit == 1)
{
this.suit = "Diamonds";
}
else if(suit ==2)
{
this.suit = "Clubs";
}
else
{
this.suit = "Hearts";
}
// convert the integer value of rank to an appropriate String
if (rank == 1)
{
this.rank = "Ace";
}
else if (rank == 11)
{
this.rank = "Jack";
}
else if (rank == 12)
{
this.rank = "Queen";
}
else if (rank == 13)
{
this.rank = "King";
}
else
{
this.rank = "" + rank;
}
}
public String getSuit()
{
return suit;
}
public String getRank()
{
return rank;
}
}
-------------------------------------------------------------------------------
public class DeckTester
{
public static void main(String[] args)
{
Deck deck1 = new Deck();;
System.out.println(deck1.toString());
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.