compareTo() 帮助(钻石比较项目)



所以我有一个项目来编写一个程序,该程序接受有关钻石的信息并进行比较。以下是提示的相关部分:

编写 compareTo() 的方法使钻石首先按胡萝卜排序,然后按净度或颜色排序,以特定钻石更好的为准。由于颜色有23个等级,但净度只有11个等级,因此将前两个颜色等级视为与一级净度相等,将后两个颜色等级与二级净度相等,依此类推。为了清楚起见,在比较代码时,您将需要一系列 if 语句。

我错过了关于接口和 compareto() 内容的讲座,但看着讲义我隐约明白了。这是我到目前为止得到的: enter code here

public class Diamond {
    String stockNumber;
    double carot;
    String clarity;
    char color;
    String cut;
    public Diamond(String startStockNumber, double startCarot, String startClarity, String startCut) {
    stockNumber = startStockNumber;
    carot = startCarot;
    clarity = startClarity;
    cut = startCut;
}
    String getStock() {
        return this.stockNumber;
    }
    double getCarot() {
        return this.carot;
    }
    String getClarity() {
        return this.clarity;
    }
    char getColor(){
        return this.color;
    }
    String getCut() {
        return this.cut;
    }
    void tooString(){
      System.out.println(this+" is stock number "+this.stockNumber+" a "+this.carot+" carot diamond with "+this.clarity+" and a "+this.cut+" cut.");
    }
    int compareTo(Diamond other) {
        if (this.carot<other.carot){
            return -1;
        }
        else if (this.carot>other.carot){
            return 1;
        }
        else{
            }
        }
    }
所以

,你正在编写一个compareTo()函数。这将命令:

  1. 按克拉重量
  2. 按最大值(净度、颜色)值。

第一个是容易的。

对于第二个,您所要做的就是将清晰度和颜色转换为数值,以使颜色/净度权衡成为简单的数字"max()"操作。然后,您将这两者的 max() 与其他菱形的 max() 进行比较。

您可以将这些位分解为几个函数:

protected int getColorValue();    // you implement this
protected int getClarityValue();  // you implement this
protected int getColorOrClarityValue() {
    int result = Math.max( getColorValue(), getClarityValue());
    return result;
}

因此:

public int compareTo (Diamond o) {
    int comp = Double.compare( getWeight(), o.getWeight());
    if (comp != 0)
        return comp;
    comp = Integer.compare( getColorOrClarityValue(), o.getColorOrClarityValue());
    return comp;
}

这应该很容易提供一个干净的解决方案。

您可以执行以下 2 件事来嵌入您提到的顺序函数。

  1. 使类钻石机具接口Comparable

    public class Diamond implements Comparable

  2. 按照托马斯上面所说的方法compareTo创建自己的订单函数。

最新更新