-1

I need to print out a deck of 52 unique cards using an ArrayList and a nested for loop. I've done this just using arrays, but I can't wrap my head around using an ArrayList instead. Any help is appreciated, thank you.

Instance Variables:

    public final String[] SUITS = {"Hearts", "Diamonds", "Spades", "Clubs"};
    public final String[] DESCRIPTIONS = {"Ace", "Two", "Three", "Four", 
                                          "Five", "Six", "Seven", "Eight", 
                                          "Nine", "Ten", "Jack", "Queen", 
                                          "King"};

    private ArrayList<Card> deck;

Method to add my deck to the ArrayList:

public void loadDeck1()
{
    deck = new ArrayList<Card>();

    for(int i = 0; i < DESCRIPTIONS.length; i++)
    {
        for(int j =0; j < SUITS.length; j++)
        {
            **deck.add(new Card(DESCRIPTIONS[i], SUITS[j])); 
            // BlueJ Error: actual and formal argument lists differ in length**
        }
    }
}

Method to Print Deck:

public void printDeck()
{
    for(Card c : deck)
    {
        System.out.println(c.getSuit() + " of " + c.getDescription());
    }
}

edit: Sorry, here's my card class!

public class Card
{
private String suit;
private String description;

/**
 * Constructor for objects of class Card
 */
public Card()
{
    suit = null;
    description = null;
}

/**
 * Accessors
 */

/**
 * @return the suit of the card
 */
public String getSuit() 
{
    return this.suit;
}

   /**
    * @return the description of the card
    */
public String getDescription()
{
    return this.description;
}

/**
 * Mutators
 */

/**
 * @param the suit of the card
 */
public void setSuit(String suit)
{
    this.suit = suit;
}

/**
 * @param the description of the card
 */
public void setDescription(String description)
{
  this.description = description;
}    

}

Stymieceptive
  • 21
  • 1
  • 6

1 Answers1

0

You need to add a constructor which takes two string(suit , description) and create an Card object for Card Class because you will use the constructor in deck.add(new Card(DESCRIPTIONS[i], SUITS[j])); statement.If you dont add this constructor,you can change description or suit variable of card object by setMethods.

public Card(String s , String d)
{
    suit = s;
    description = d;
}

If you want to use ArrayList instead of arrays for instance variables.

public ArrayList<String> SUITS = add("Hearts");
ArrayList<String> SUITS = add("Diamonds");
ArrayList<String> SUITS = add("Spades");
ArrayList<String> SUITS = add("Clubs");

public ArrayList<String> DESCRIPTIONS = add("Ace");/...
//and add elements of descriptions arrayList

You can also pass an ArrayList a normal for loop instead of for each loop.

Needed to change some part of codes:

for(int i = 0; i < DESCRIPTIONS.size(); i++)
{
    for(int j =0; j < SUITS.size(); j++)
    {
        **deck.add(new Card(DESCRIPTIONS.get(i), SUITS.get(j))); 
    }
} 
Ediz Uslu
  • 119
  • 4