我让我的代码更加充实了(我将所有内容整合到主要方法中。我认为应该有所帮助。
无论如何我收到此错误
Exception in thread "main" java.lang.ClassCastException: lab13d.Card cannot be cast to java.lang.Comparable
at java.util.PriorityQueue.siftUpComparable(PriorityQueue.java:652)
at java.util.PriorityQueue.siftUp(PriorityQueue.java:647)
at java.util.PriorityQueue.offer(PriorityQueue.java:344)
at java.util.PriorityQueue.add(PriorityQueue.java:321)
at lab13d.Lab13d.main(Lab13d.java:53)
Java Result: 1
不能做出头脑或尾巴。我之前从未使用过队列,所以这对我来说真的很新。
这是我的代码:
public static void main(String[] args)
{
int players = 2;
Card[] pile;
int MAX_CARDS = 52;
int MAX_SUITS = 4;
int MAX_RANKS = 14;
pile = new Card[MAX_CARDS];
int index = 0;
for(int suit = 1; suit <= MAX_SUITS; suit++){
for(int rank = 2; rank <= MAX_RANKS; rank++, index++ ){
Card c = new Card(suit, rank);
pile[index] = c;
}
}
PriorityQueue<Card>[] hand = new PriorityQueue[players + 1];
for(int i = 0; i < players + 1; i++){
hand[i] = new PriorityQueue();
}
for(int i = 0; i < players; i++){
for(int j = i; j < pile.length; j+= players){
hand[i].add(pile[j]);
}
}
int leftOverCards = pile.length - (pile.length % players);
for(int i = leftOverCards; i < pile.length; i++){
hand[players].add(pile[i]);
}
System.out.printf("%s", hand[0]);
}
答案 0 :(得分:2)
我假设以下行抛出ClassCastException:
hand[i].add(pile[j]);
您正在尝试将卡片的实例添加到PriorityQueue,显然您的卡片无法进行比较。您需要转到Card.java文件并使该类实现Comparable接口:
public class Card implements Comparable<Card>{
...
...
...
您还需要实现compareTo方法,我假设您的卡将按其值进行比较,并且Card对象的int属性值范围为2(a 2)到13(ace)。如果价值相等,我们可以通过诉讼进行比较 - 我将把这部分留给自己:
@Override
public int compareTo(Card o) {
int comparisonOutcome = ((Integer)o.getValue()).compareTo((Integer)this.getValue());
if(comparisonOutcome == 1 || comparisonOutcome == -1){
return comparisonOutcome;
else{
// here values are equal, we can compare by card suit
// return -1, 1 or 0
}
我希望它有所帮助。