Java 无法解析方法';比较(int)和#x27 ;;
我正在尝试使用冒泡排序和compareTo方法对对象数组进行排序。“。IF条件中的compareTo不起作用,并表示无法解析方法“compareTo(int)”,如何解决此问题 我的排序方法:Java 无法解析方法';比较(int)和#x27 ;;,java,arrays,sorting,comparison,bubble-sort,Java,Arrays,Sorting,Comparison,Bubble Sort,我正在尝试使用冒泡排序和compareTo方法对对象数组进行排序。“。IF条件中的compareTo不起作用,并表示无法解析方法“compareTo(int)”,如何解决此问题 我的排序方法: public static void sort(Card[] hand) { for (int i = 1; i < hand.length; i++) { for (int j = 0; j < hand.length - i; j++) {
public static void sort(Card[] hand) {
for (int i = 1; i < hand.length; i++) {
for (int j = 0; j < hand.length - i; j++) {
if (((hand[j].getRankValue()).compareTo((hand[j + 1].getRankValue()))) > 0) {
Card temp = hand[j];
hand[j] = hand[j + 1];
hand[j + 1] = temp;
}
}
}
}
}您的compareTo()
函数比较两张卡,因此在if
语句中不需要任何getRankValues()
。如果你摆脱了这些,你的代码应该可以工作
public final int suit;
public final int rank;
public int rankValue = 0;
public static final String[] SUIT = {
"Hearts", "Clubs", "Diamonds", "Spades"};
public static final String[] RANK = {
"2", "3", "4", "5", "6", "7",
"8", "9", "10", "Jack", "Queen", "King", "Ace"};
public Card(int rank, int suit) {
this.rank = rank;
this.suit = suit;
this.rankValue = getRankValue();
}
public int compareTo(Card other){
if(getRankValue() > other.getRankValue()) return 1;
else if(getRankValue() < other.getRankValue()) return -1;
else return 0;
}
public int getRank(){
return this.rank;
}
public int getSuit(){
return this.suit;
}
public int getRankValue() {
return this.suit * 13 + this.rank - 1;
}
public String toString() {
return RANK[this.rank] + " of " + SUIT[this.suit];
}