I need to add a shuffle() constructor which randomizes the deck, and returns no
ID: 3733157 • Letter: I
Question
I need to add a shuffle() constructor which randomizes the deck, and returns no value.
I also need to add a dealOneCard() constructor - which returns one card from the deck to the user(returns one card at a time). Specifically, a call to
shuffle() followed by 52 calls to dealOneCard() should result in the user being provided
all 52 cards of the deck in a random order. If the caller then makes a 53rd call
dealOneCard(), no card is dealt.
Probaly needs to be another class as well.
public class Cards {
public static void main(String[] args)
{
int[] deck = new int[52];
String[] suits = { "Spades", "Hearts", "Diamonds", "Clubs" };
String[] ranks = { "2", "3", "4", "5", "6", "7", "8", "9", "10","Ace", "Jack", "Queen", "King" };
for (int i = 0; i < deck.length; i++)
deck[i] = i;
for (int i = 0; i < deck.length; i++)
{
int shuffle = (int) (Math.random() * deck.length);
int temp = deck[i];
deck[i] = deck[shuffle];
deck[shuffle] = temp;
}
for (int i = 0; i < 52; i++)
{
String suit = suits[deck[i] / 13];
String rank = ranks[deck[i] % 13];
System.out.println("card number " + deck[i]+": "+rank + " of " + suit);
}
}
}
Explanation / Answer
Your approach can be like this.
Include public variables deck, suits, ranks can be inherited by the child class Shuffle.
In the child class Shuffle, include a constructor Shuffle() and there use the logic Math.random() * deck.length.
Also include a class dealOneCard and include a constructor dealOneCard(). You can use the logic
for (int i = 0; i < deck.length; i++)
{
int shuffle = (int) (Math.random() * deck.length);
int temp = deck[i];
deck[i] = deck[shuffle];
deck[shuffle] = temp;
}
To call shuffle once followed by calling 52 times DealOneCard, the following loop can be useful.
for( i=1; i<=52; i++)
{
ob.shuffle();
ob[i].dealOneCard();
}
where ob is an object of the last child class in the hierarchy.
NOTE: A better and clear explanation of question is always helpful for the teacher and as well as for the student, for understanding the appropriate problem.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.