My assignment asks to create a constructor that takes no input. The constructor initializes the two non-static attributes in order for them to represent a standard deck or cards. Note that this means that the array of Cards should be initialized with an array of 52 elements containing all 52 possible cards belonging to a standard deck. You must use at least 1 loop to accomplish this (that is, you cannot write 52 statements to assign all possible values).
Hint: If you create a String array of size 4 with all the possible suits value in it, you can easily use two nested loops to initialize the array of cards.
I started writing my code, but I have trouble understanding what they mean by the hint. I know I have to create a multi-dimensional array and loop through the elements, but can't figure how to create that multi-dimensional array.
Here is my code:
public class Deck {
// Declare the private attributes
private Card[] cards;
private int numberOfCardsLeft;
// Access the private fields via public methods
// Generate a constructor
public Deck() {
this.cards = new Card[][];
// Iterate through all the elements of the array
for (int i = 0; i < 4; i++) {
// Iterate through all the elements of the subarrays
for (int j = 0; j < 13; j++) {
// code missing
}
}
}
}
Here is the Card class:
public class Card {
// Declare the private attributes
private int cardValue;
private String cardSuit;
// Access the private fields via public methods
// Generate a constuctor
public Card(int value, String suit) {
this.cardValue = value;
this.cardSuit = suit.toLowerCase();
// Check if the input is a valid playing card
if (!(this.cardValue >= 1 || this.cardValue <= 13) && (this.cardSuit.equals("spades") || this.cardSuit.equals("hearts") || this.cardSuit.equals("diamonds") || this.cardSuit.equals("clubs"))) {
// Throw an IllegalArgumentException
throw new IllegalArgumentException("This is not a valid playing card!");
}
}
public int getValue() {
return cardValue;
}
public String getSuit() {
return cardSuit;
}
}
Here is my getCards() method:
// A get() method that returns an array of Cards containing all the cards that are left in the deck
public Card[] getCards() {
// Create a copy of the original array
Card[] cardsLeft = new Card[cards.length];
// Iterate through all the elements of the array
for (int i = 0; i < cardsLeft.length; i++) {
cardsLeft[i] = cards[i];
}
return cardsLeft;
}