好的,在下面的代码中,我想声明“钻石”和“红心”是红色的。
代码在这里
if (card.getCardFace() == || card.getCardFace() == )
g.setColor(Color.red);
else
g.setColor(Color.black);
如果我在Card类中将它们声明为chars,我想知道如何才能做到这一点。我必须改变吗?
卡类
// 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);
}
}
(如果您需要更多代码,请告诉我)
答案 0 :(得分:2)
您应该使用Enums
来定义排名和套装的类型,例如:
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;
}
然后只比较值:
if (card.suit == Suit.DIAMONDS || card.suit == Suit.HEARTH) {
color = Color.RED;
} else {
color = Color.BLACK;
}
或者将颜色定义为Suit
的属性,然后使用:
color = card.suit.getColor();