Making a deck of cards on Java using arrays and objects?

2k views Asked by At

My textbook gave me this code saying that it'll create a new set of 52 cards. I don't really understand what it does, because the methods I see on google is very different from this. I'm confused about what the "index" variable does and how can I print this method? I do have a printdeck method but how would I call that method if this method doesn't return any number?

 public static void buildDeck () {
    Card[] deck = new Card [52];
 int index = 0;
 for (int suit = 0; suit <=3; suit++) {
     for (int rank = 1; rank <= 13; rank++) {
         deck[index] = new Card (suit, rank);
         index++;
     }

}

//here is my printDeck method
public static void printCard (Card c) {
    String[] suits = { "Clubs", "Diamonds", "Hearts", "Spades" };
    String [] ranks = { "nart", "Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "jack", "Queen", "king" };
    System.out.println (ranks[c.rank] + " of " + suits[c.suit]);
}
public static void printDeck (Card[] deck) {
    for (int i = 0; i< deck.length; i++) {
        printCard (deck[i]);
    }
}

I'll appreciate any help, thanks!

3

There are 3 answers

0
Rainer Wei On

The index variable, like the name states, is used as a counting index for the deck.

The printDeck(..) method should print the whole to the console by calling the printCard(..) method and that method in return calling System.out.println

2
Stefan Freitag On
  • The method printDeck doesn not really print something to the console. It takes an array of cards and calls for each card the method printCard (supplying the current card as argument).
  • The method printCard takes - as mentioned before - a single card and prints its rank /suite to the console.

    public static void printCard (Card c) { System.out.println (ranks[c.rank] + " of " + suits[c.suit]); }

The index variable is used e.g. to initialize the deck of cards.

  • Initially you have 52 "blank" cards in the array, or better said each entry in the array is null.
  • In each iteration you are creating a new Card and have to assign it to a position in the deck. This is done via the index and by incrementing it with each iteration.
0
Vicky Desai On

You should return card[] deck from your buildDeck method and then pass it to print method.