java - String.compareTo方法进行比较

标签 java compareto

你能检查一下我的方法并让我知道我做错了什么吗?谢谢你:)

public static void sortByVehicleMakeModel(Vehicle[] vehicles) {
    boolean swapped = true;

    for(int y = 0; y < vehicles.length && swapped; y++) {
        swapped=false;
        for(int x = 0; x < vehicles.length - (y+1); x++) {
            if(vehicles[x].getMake() && vehicles[x].getModel().compareTo(vehicles[x + 1].getMake() && vehicles[x].getModel())) {    
                swap(vehicles, x, x + 1);
                swapped=true;
            }
        }
    }
}

我的错误出现在第二条语句 .compareto() 上 对于参数类型 java.lang.String、java.lang.String ,运算符 && 未定义

但是,这段代码运行得很好:

public static void sortByOwnerName(Vehicle[] vehicles) {
    boolean swapped = true;

    for(int y = 0; y < vehicles.length && swapped; y++) {
        swapped=false;
        for(int x = 0; x < vehicles.length - (y + 1); x++) {
            if(vehicles[x].getOwner().getName().compareTo(vehicles[x + 1].getOwner().getName())> 0) {   
                swap(vehicles, x, x + 1);
                swapped=true;
            }
        }
    }
}

最佳答案

我建议将 int getCost() 添加到 Vehicle 对象,然后使用 vehicles[x].getCost() > cars[x - 1].getCost() 用于 if 语句。

而且,这种排序效率不是很高。也许车辆应该实现 Comparable并使用Collections.sort()进行排序。

<小时/>

请阅读您的问题的更新。

试试这个:

if (vehicles[x].getMake().compareTo(vehicles[x - 1].getMake()) < 0 || 
   (vehicles[x].getMake().compareTo(vehicles[x - 1].getMake()) == 0 &&
    vehicles[x].getModel().compareTo(vehicles[x - 1].getModel()) < 0)) {

关于java - String.compareTo方法进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13428071/

相关文章:

java - 在克隆对象时需要一些关于我的逻辑的帮助

java - 使用 compareTo 实现 equals 方法

java - eclipse RCP : class loading problem

java - 将 String 转换为 Long 时出现 Scala NumberFormatException?

java - 为什么使用 Arial Unicode MS 无法正确呈现古吉拉特语-印度文本?

java - Spring继承,多对多,实体映射中的重复列

c# - 为什么使用 TimeSpan.CompareTo() 而不是 < > 或 =

Java CompareTo 对于不工作的对象

Java compareTo() 方法返回 classCastException

java - 在GGTS 3.6.4上进行调试。RELEASE无法检查并抛出异常:ContentTypeUtils.isGroovyLikeFileName(Ljava/lang/String;)Z