Dylan Dylan - 3 months ago 29
Java Question

Creating a deck of cards in java with a two dimensional array

so I am attempting to create a deck and apply a suite to each one, for example:

cardValue[0][1] and convert it into cardValue[Spade][1]

but I don't understand how to convert it into that, what I have currently:

int cardValues[][];
for(int a = 0; a <= 3; a++)
{
for(int b = 0; b <= 12; b++)
{
cardValues[][] += cardValues[a][b];
if(cardValues[a][b] == cardValues[a][0])
{
cardValues[a][b] = 5;
}
else if(cardValues[a][b] > cardValues[a][0] || cardValues[a][b] < cardValues[a][10])
{
cardValues[a][b] = 1;
}
else if(cardValues[a][b] == cardValues[a][10])
{
cardValues[a][b] = 2;
}
else if(cardValues[a][b] == cardValues[a][11])
{
cardValues[a][b] = 3;
}
else if(cardValues[a][b] == cardValues[a][12])
{
cardValues[a][b] = 4;
}
}
}


I don't understand how to convert the 0, 1, 2, and 3 into spades, diamonds, clubs, hearts.

Answer

I would do something like that:

Suit.java

public enum Suit {
    SPADES, DIAMONDS, CLUBS, HEARTS
}

Card.java

public class Card {

    private Suit suit;
    private String value;

    public Card(Suit suit, String value) {
        this.suit = suit;
        this.value = value;
    }

    public Suit getSuit() {
        return suit;
    }
    public void setSuit(Suit suit) {
        this.suit = suit;
    }
    public String getValue() {
        return value;
    }
    public void setValue(String value) {
        this.value = value;
    }

}

Main.java

public class Main {

    public static void main(String[] args) {

        String[] values = new String[]{"K", "Q", "J", "10", "9", "8", "7", "6", "5", "4", "3", "2", "A"};

        Card[] deck = new Card[52];

        int i = 0;
        for (Suit suit : Suit.values()) {
            for (String value : values) {
                deck[i++] = new Card(suit, value);
            }
        }

        for (Card card : deck) {
            System.out.println(card.getValue() + " of " + card.getSuit());
        }

    }

}
Comments