【问题标题】:Cannot resolve method 'CompareTo(int)' [closed]无法解析方法“CompareTo(int)”[关闭]
【发布时间】:2021-03-03 11:45:27
【问题描述】:

我正在尝试使用冒泡排序和 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++) {
            if (((hand[j].getRankValue()).compareTo((hand[j + 1].getRankValue()))) > 0) {
                Card temp = hand[j];
                hand[j] = hand[j + 1];
                hand[j + 1] = temp;
            }
        }
    }
}

public class Card {

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];
}

}

【问题讨论】:

    标签: java arrays sorting comparison bubble-sort


    【解决方案1】:

    您的compareTo() 函数比较两张卡片,因此您的if 语句中不需要任何getRankValues()。如果你摆脱了这些,你的代码应该可以工作。

    【讨论】:

      猜你喜欢
      • 2018-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-08
      • 1970-01-01
      • 2015-03-30
      • 1970-01-01
      • 2015-08-30
      相关资源
      最近更新 更多