gpt4 book ai didi

java - 基于对象的两个值进行比较

转载 作者:行者123 更新时间:2023-12-02 06:45:14 28 4
gpt4 key购买 nike

我正在开发一个“特许经营”程序,该程序具有所有者、状态和销售额,这些都在构造函数中设置并且无法更改。当我尝试编写compareTo方法时,我的问题就出现了。

package prob2;

public class Franchise implements Comparable <Franchise> {
final String owner;
final String state;
final double sales;

protected Franchise(String owner, String state, double sales ) {
this.owner = owner;
this.state = state;
this.sales = sales;
}

public String toString() {
String str = state + ", " + sales + ", " + owner;
return str;
}

public String getState() {
return state;
}

public double getSales() {
return sales;
}
public int compareTo(Franchise that) {
double thatSales = that.getSales();
if (this.getState().compareTo(that.getState()) <0)
return -1;
else if (this.getSales() > thatSales)
return -1;
else if (this.getSales() < thatSales)
return 1;
else
return 0;
}

程序应实现可比较的接口(interface),并应根据状态升序和销售额降序比较特许经营对象。我的问题是如何使用这两个值进行比较,有没有办法在一次比较中进行比较,或者我是否需要多个比较器?

示例:

州 = CA,销售额 = 3300 与州 = NC,销售额 = 9900 相比将返回负值

州 = CA,销售额 = 3300 与州 = CA,销售额 = 1000 相比将返回负值

州 = CA,销售额 = 3300 与州 = CA,销售额 = 9900 相比将返回正值

感谢您的所有帮助。

最佳答案

is there a way to do it in a single compare, or do i need multiple compareators?

就您而言,您不需要多个比较器。只需在单个 compareTo 方法中编写基于这两个属性的逻辑,如下所示:

public int compareTo(Franchise that) {
if (this.getState().equals(that.getState()) {
// Compare on the basis of sales (Take care of order - it's descending here)
} else {
// Compare on the basis of states.
}
}

关于java - 基于对象的两个值进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18722974/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com