gpt4 book ai didi

java - 对卡片对象进行排序

转载 作者:行者123 更新时间:2023-11-30 03:36:59 25 4
gpt4 key购买 nike

我正在创建一个简单的纸牌游戏,我希望能够对 ArrayList<Card> 进行排序以便玩家的手牌更容易阅读。现在我有:

卡片类别:

public class Card implements Comparable {

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

public enum Values {
TWO,
THREE,
FOUR,
FIVE,
SIX,
SEVEN,
EIGHT,
NINE,
TEN,
JACK,
QUEEN,
KING,
ACE,
}

private Suits suit;
private Values value;

public Card(final Values value, final Suits suit) {
this.value = value;
this.suit = suit;
}

public Values getValue() {
return value;
}

public Suits getSuit() {
return suit;
}

public void showCard() {
value = getValue();
suit = getSuit();

System.out.println(value + " of " + suit);
}

public int compareTo(final Object compareCard) {
Card compareToCard = (Card) compareCard;
Suits thisSuit = this.suit;
Values thisValue = this.value;

if (thisSuit.ordinal() == compareToCard.getSuit().ordinal() &&
thisValue.ordinal() == compareToCard.getValue().ordinal()) {
return 0;
}
else if (thisSuit.ordinal() == compareToCard.getSuit().ordinal()) {
if (thisValue.ordinal() > compareToCard.getValue().ordinal()) {
return 1;
}
else {
return -1;
}
}
else {
return -1;
}
}

}

我使用了ordinal值,因为我想对值 2-Ace 进行排序,只要它们组合在一起,花色的顺序并不重要。

然后我有一个ArrayList<Card>playerHand 。我正在尝试使用以下方法进行排序:

playerHand.sort();

当我编译此代码时,我收到一个错误:

error: method sort in interface List<E> cannot be applied to given types;
playerHand.sort();
^
required: Comparator<? super Card>
found: no arguments
reason: actual and formal argument lists differ in length
where E is a type-variable:
E extends Object declared in interface List

我不太确定我做错了什么。任何帮助将不胜感激!

最佳答案

您需要实现 Comparable 接口(interface),如下所示:

public class Card implements Comparable<Card> {

关于java - 对卡片对象进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27640355/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com