【发布时间】:2020-03-07 10:01:34
【问题描述】:
我正在尝试开发一个 Java 程序,它是一个使用枚举类型/类来表示扑克牌的游戏。我想使用枚举类型来表示可能的套装和可能的等级。游戏从一副牌中随机抽取两张牌并进行比较。
我有 4 个类,即 SimpleCardGame、Card、Rank 和 Suit。目前,我遇到了 SimpleCardGame 和 Card 的问题。
对于 SimpleCardGame,我唯一的问题是实例化一副纸牌。我做错了什么?一旦我能够解决这个问题,“您不必修改下面的任何内容”下面的整个部分都会完美运行。
对于 Card,有一个名为 public int compareTo(Card c) 的方法返回
一个。 -1 如果调用此方法的对象小于 c
b. 0 如果调用该方法的对象与 c 相同
c。 1 如果调用此方法的对象大于 c
如果c1的点数小于c2,或者c1和c2的点数相同,c1的花色小于c2,则c1小于c2。 花色顺序:黑桃>红心>梅花>菱形 排名顺序:A > K > Q > J > 10 > 9 > 8 > 7 > 6 > 5 > 4 > 3 > 2
所以我的问题是如何比较卡值?我正在考虑使用序数值方法,但我不太清楚如何使用它。
public class SimpleCardGame {
public static void main(String[] args) {
Card cards[]; // an array of Cards, representing a deck of cards
// put a copy of each card into cards
// The order of the cards in the array is:
// S2, S3, ..., SK, H2, ..., HK, C2, ..., CK, D2, ..., DK
int i = 0;
for (Suit s : Suit.values()) {
for (Rank r : Rank.values()) {
cards[i]= new Card(s,r);
i++;
}
}
}
//
// YOU DO NOT HAVE TO MODIFY ANYTHING BELOW
//
// print out the whole deck once
System.out.println("The whole deck is:");
for (Card card : cards)
System.out.print(card + " ");
System.out.println();
// randomly draw two cards
MyRandom rnd = new MyRandom();
Card c1 = cards[rnd.nextInt(cards.length)-1];
Card c2 = cards[rnd.nextInt(cards.length)-1];
System.out.println("Two cards are drawn:");
System.out.println("c1 = " + c1 + " and c2 = " + c2);
// compare c1 and c2
if (c1.compareTo(c2) < 0) {
System.out.println(c1 + " is smaller than " + c2);
}
else if (c1.compareTo(c2) == 0) {
System.out.println(c1 + " is the same as " + c2);
}
else {
System.out.println(c1 + " is larger than " + c2);
}
}
}
public class Card {
private Rank rank;
private Suit suit;
public Card (Suit suit, Rank rank) {
this.rank = rank;
this.suit = suit;
}
public String toString() {
return suit + "" + rank;
}
public int compareTo(Card c) {
int diffRank = rank - c.rank;
if (diffRank < 0) {
return -1;
}
else if (diffRank > 0) {
return 1;
}
else if (diffRank == 0) {
int diffSuit = suit - c.suit;
if (diffSuit < 0) {
return -1;
}
else if (diffSuit > 0) {
return 1;
}
}
return 0;
}
}
public 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 String rank;
// Constructor
Rank (String r) {
rank = r;
}
public String toString() {
return rank;
}
}
public enum Suit {
SPADE("S"),
HEART("H"),
CLUB("C"),
DIAMOND("D");
private String suit;
Suit (String s) {
suit = s;
}
public String toString() {
return suit;
}
}
下面是该程序的假定示例输出。
The whole deck is:
S2 S3 S4 S5 S6 S7 S8 S9 S10 SJ SQ SK SA H2 H3 H4 H5 H6 H7 H8 H9 H10 HJ HQ HK HA C2 C3 C4 C5 C6 C7 C8 C9 C10 CJ CQ CK CA D2 D3 D4 D5 D6 D7 D8 D9 D10 DJ DQ DK DA
Two cards are drawn:
c1 = S7 and c2 = HQ
S7 is smaller than HQ
【问题讨论】:
-
您的问题到底是什么?程序的输出似乎是正确的?整个甲板都在那里?s7确实比hq小?
-
这是应该输出的,但现在我在 SimpleCardGame 类中遇到错误