Search code examples
javablackjack

How can I declare the suits Diamond and Hearts?


Okay in the code below I want to declare that "Diamonds" and "Hearts" are red.

Code Here

if (card.getCardFace() == || card.getCardFace() == )
            g.setColor(Color.red);
         else
           g.setColor(Color.black);

I was wondering on how I could do that if I declared them as chars in my Card class. Do I have to change that ?

Card Class

// Instance Data - all things common to all cards
private String cardFace; // king, q, j, 10 - 2, A
private int faceValue; // numberic value of the card
private char cardSuit; // hold suit of the card
private char suits[] = {(char)(003), (char)(004), (char)(005), (char)(006)};

// Constructor
public PlayingCard(int value, int suit)
{
    faceValue = value;
    setFace();
    setSuit(suit);
}

// helper setFace()
public void setFace()
{
    switch(faceValue)
    {
        case 1:
            cardFace = "A";
            faceValue = 14;
            break;
        case 11:
            cardFace = "J";
            break;
        case 12:
            cardFace = "Q";
            break;
        case 0:
            cardFace = "K";
            faceValue = 13;
            break;
        default:
            cardFace = ("" + faceValue);
    }
}

public void setSuit(int suit) // suit num between 0 and 3
{
    cardSuit = suits[suit];
}

// other helpers
public int getFaceValue()
{
    return faceValue;
}
public String getCardFace()
{
    return cardFace;
}

public String toString()
{
    return (cardFace + cardSuit);
}
}

(Also let me know if you need more code)


Solution

  • You should use Enums to define types for ranks and suits, something like:

    public static enum Suit {
        CLUB, DIAMOND, SPADE, HEART
    }
    
    public static enum Rank {
        TWO("2"), THREE("3"), FOUR("4"), FIVE("5"), SIX("6"), SEVEN("7"), 
        EIGHT("8"), NINE("9"), TEN("10"), JACK("J"), QUEEN("Q"), KING("K"), 
        ACE("A");
    
        private final String symbol;
    
        Rank(String symbol) {
            this.symbol = symbol;
        }
    
        public String getSymbol() {
            return symbol;
        }
    }
    
    ---
    
    class Card {
        Suit suit;
        Rank rank;
    }
    

    Then just compare the values:

    if (card.suit == Suit.DIAMONDS || card.suit == Suit.HEARTH) {
        color = Color.RED;
    } else {
        color = Color.BLACK;
    }
    

    Or define a color as a property of Suit and then just use:

    color = card.suit.getColor();