我想在扑克手牌中比较两张牌...他们每个人都有一套西装和一个等级我想检查是否有重复创建例外..请帮助这段代码!是否可以使用equals方法或它是错误的?!
import java.util.ArrayList;
public class Pokerhand {
public final int CARDS_NUMBER = 5;
ArrayList<Card> cards = new ArrayList<Card>();
public Pokerhand (Card card1 , Card card2, Card card3, Card card4, Card card5)
{
cards.add(card1);
cards.add(card2);
cards.add(card3);
cards.add(card4);
cards.add(card5);
}
private boolean check(ArrayList<Card> cards)
{
if (cards.size() != CARDS_NUMBER)
throw new IllegalArgumentException("Incorrect number of cards!! ");
for ( int i=0 ; i<= cards.size(); i++)
{
if (cards.get(i).equals(cards.get(i+1)))
throw new IllegalArgumentException("Duplicat card");
}
}
}
答案 0 :(得分:0)
您应该覆盖equals
方法,或者只是比较两个对象的引用,而不是卡片的值。
这是一个例子:
public class Card {
private int rank;
private int suit;
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Card)) {
return false;
}
Card c = (Card) obj;
return this.rank == c.rank && this.suit == c.suit;
}
}
答案 1 :(得分:0)
您应该考虑在Card类中实现Comparable。假设每张卡都有等级(1-king)和套装(心形,钻石等)方法compareTo看起来像:
public int compareTo(Card anotherCard) {
if (this.suit.equals(anotherCard.suit) && this.rank.equals(anotherCard.rank)) {
return 0;
}
else if (this.suit.equals(anotherCard.suit)) {
return this.rank.compareTo(anotherCard.rank);
}
else {
return this.suit.compareTo(anotherCard.suit);
}
}
然后你应该使用card1.compareTo(card2)== 0而不是card1.equals(card2)
答案 2 :(得分:0)
而不是
if (cards.get(i).equals(cards.get(i+1)))
throw new IllegalArgumentException("Duplicat card");
尝试:
if(cards.get(i).getSuit() == cards.get(i+1).getSuit()
&& cards.get(i).getRank() == cards.get(i+1).getRank())
throw new IllegalArgumentException("Duplicat card");
这样您就可以比较对象中的值,而不是比较对象引用是否相同。
答案 3 :(得分:0)
您可以使用枚举更好地建模。例如:
import java.util.EnumSet;
public class PokerGame {
public enum Suit {
SPADES, HEARTS, DIAMONDS, CLUBS
}
public enum Rank {
ACE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGH, NINE, TEN, JACK, QUEEN, KING
}
public enum Card {
ACE_OF_SPADES(Rank.ACE, Suit.SPADES),
TWO_OF_SPADES(Rank.TWO, Suit.SPADES),
THREE_OF_SPADES(Rank.THREE, Suit.SPADES),
FOUR_OF_SPADES(Rank.FOUR, Suit.SPADES),
FIVE_OF_SPADES(Rank.FIVE, Suit.SPADES);
// the other cards left as an exercise for the reader (-;
private Rank rank;
private Suit suit;
Card(Rank rank, Suit suit) {
this.rank = rank;
this.suit = suit;
}
public Rank rank() {
return rank;
}
public Suit suit() {
return suit;
}
}
public static void main(String[] args) {
EnumSet<Card> deck = EnumSet.allOf(Card.class);
System.out.println(deck.size());
}
}
然后,您可以使用EnumSet创建卡片组或卡片组,始终保证是唯一的。
补充说明,以下逻辑存在缺陷:
for ( int i=0 ; i<= cards.size(); i++)
{
if (cards.get(i).equals(cards.get(i+1)))
throw new IllegalArgumentException("Duplicat card");
}
这将抛出一个IndexOutOfBoundsException,因为你正在迭代到cards.size()并且访问cards.get(i + 1)。此外,这不会检测不相邻的重复项。