Write an immutable class named Card torepresent a playing card object. Its priva
ID: 3763975 • Letter: W
Question
Write an immutable class named Card torepresent a playing card object. Its private instance variablesshould be an int rank and a String suit. You should have onlyone constructor that takes a rank and a suit as arguments.Your constructor should check if the rank and suit are valid!
Hint: valid ranks are between 2 and 14 (11 = jack, 12 = queen,13 = king, 14 = ace). For checking the suit, make literal arrayof valid suits.
You should have methods that access the instance variablesvalues (i.e. getter methods). Also, since we may want tocompare cards, you should write three comparison methods(equals, greaterThan, lessThan as in the lab), following thisorder: compare by rank first (i.e. 2 < 3 < 4 < ... < 14), if theyare tied then compare suits (clubs < diamonds < hearts <spades).
Can you indicate which is constructor?
Explanation / Answer
class Card
{
static final String[] Suit = {"Clubs", "Diamonds", "Hearts", "Spades" };
static final String[] Rank = {"","A","2","3","4","5","6","7","8","9","10","J","Q","K"};
private int cardRank;
private int cardSuit;
public Card(int rank, int suit) throws PlayingCardException
{
if ((rank < 1) || (rank > 13))
throw new PlayingCardException("Invalid rank:"+rank);
else
cardRank = rank;
if ((suit < 0) || (suit > 3))
throw new PlayingCardException("Invalid suit:"+suit);
else
cardSuit = suit;
}
public int getRank()
{
return cardRank;
}
public int getSuit()
{
return cardSuit;
}
public String toString()
{
return Rank[cardRank] + " " + Suit[cardSuit];
}
public static void main(String args[])
{
try
{
Card c1 = new Card(1,3);
System.out.println(c1);
c1 = new Card(10,0);
System.out.println(c1);
//c1 = new Card(10,5);
}
catch (PlayingCardException e)
{
System.out.println("PlayingCardException: "+e.getMessage());
}
}
}
Deck class:
class Decks
{
private List<Card> originalDecks;
private List<Card> dealDecks;
private int numberDecks;
/**
* Constructor: Creates default one deck of 52 playing cards in originalDecks and
* copy them to dealDecks.
* initialize numberDecks=n**/
public Decks(int n) throws PlayingCardException
{
int i, j;
for (i=0;i<4;i++)
{
for(j=1;j<14;j++)
{
for(k=0;k<n;k++)
{
Card orcard = new Card(i,j);
originalDecks.add(orcard);
dealDecks.add(orcard);
}
}
}
/**
* Constructor: Creates n decks (52 cards each deck) of playing cards in
* originalDecks and copy them to dealDecks.
* initialize numberDecks=n
*/
public Decks(int n) throws PlayingCardException
{
int i, j;
for (i=0;i<4;i++)
{
for(j=1;j<14;j++)
{
Card orcard = new Card(i,j);
originalDecks.add(orcard);
dealDecks.add(orcard);
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.