Nguyen13
Nguyen13

Reputation: 15

Create a Deck of Cards with Two Arrays

I am working on a Java experiment to make a deck of cards. So far, I managed to get the card class working. This sets up card with getter and setter methods for rank and suit and a toString method. One of the instructions in the deck class says to create a deck, using a Card object for every combination of rank and suit. I'm not confident on how to do this and was wondering if anyone could point me in the right direction? So far this is the code I have:

public class Deck
{
    public static final int number = 52;

Upvotes: 0

Views: 1193

Answers (2)

mrhn
mrhn

Reputation: 18916

You are not declaring your logic in a scope, you are declaring it in the class definitions. You need to put your logic in a Method or The class Main Method. I think for the moment you are biting off more you can chew, follow simple tutorials and get an understanding of basic Java concepts, like method declaration, field declaration, main methods etc. Before you are start on working on fancy logic. Happy coding.

public class Deck
{
    public static final int number = 52;

    String[] ranks = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"};
    String[] suits = {"Clubs", "Diamonds", "Hearts", "Spades"};

    public Card[] deck = new Card[number];

    public void CreateDeck()
    {
        int i = 0;
        for(String suit : suits) {
            for(String rank : ranks) {
               deck[i++] = new Card(suit, rank);
            }
        }
    }
}

Upvotes: 1

camickr
camickr

Reputation: 324108

Your class doesn't have a constructor (or some method you can invoke). The looping code should be in the constructor.

public class Deck
{
    public static final int number = 52;

    String[] ranks = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"};
    String[] suits = {"Clubs", "Diamonds", "Hearts", "Spades"};

    //Card[] deck = NUM_CARDS;
    //int i = 0; 

    public Deck()
    {
        for(String suit : suits) {
             for(String rank : ranks) {
                deck[i++] = new Card(suit, rank);
             }
        }
    }

You need to define your Array correctly.

Card[] deck = new Card[number];

Upvotes: 0

Related Questions