[英]Issues utilizing the comparable interface
我試圖利用可比的接口對數組進行排序。 編寫方法compareTo(),以便首先按菱形排序鑽石,然后按凈度或顏色排序,以特定鑽石為佳。 由於有23種顏色等級,但只有11種透明度,因此將前兩個顏色等級等同於第一個透明度等級,將后兩個顏色等級等同於第二個透明度等級,依此類推。 我不確定如何比較顏色和清晰度,因為一個是字符串,另一個是字符。 這是我到目前為止所擁有的。
public Diamond(String sN, double car, String clar, char col, String cutType)
{
stockNumber = sN;
carot = car;
clarity = clar;
color = col;
cut = cutType;
}
public int compareTo(Diamond other)
{
if (getCarot() < other.getCarot())
{
return 1;
}
else if(getCarot() > other.getCarot())
{
return -1;
}
else return 0;
}
public String toString()
{
return "{stockNumber :: " +getStock() + " carot :: " +getCarot() + " clarity :: " +getClarity()+ " color :: " +getColor() + " cut :: " +getCut()+"}";
}
//gets the stock number of the diamond
public String getStock()
{
return stockNumber;
}
//gets the carot size of the diamond
public double getCarot()
{
return carot;
}
//gets the clarity of the diamond
public String getClarity()
{
return clarity;
}
//gets the color of the diamond
public char getColor()
{
return color;
}
//gets the cut of the diamond
public String getCut()
{
return cut;
}
Diamond []寶石=新Diamond [16];
stones[0] = new Diamond( "A1023", 1.0, "VS1", 'F', "brilliant");
stones[1] = new Diamond( "A5911", 1.1, "VVS2", 'G', "rose");
stones[2] = new Diamond( "C5427", 1.0, "VS1", 'D', "princess");
stones[3] = new Diamond( "D8307", 1.6, "SI1", 'H', "brilliant");
stones[4] = new Diamond( "B4825", 0.3, "I1", 'D', "rose");
stones[5] = new Diamond( "A1844", 2.1, "VS2", 'D', "lozenge");
stones[6] = new Diamond( "A3747", 3.1, "SI2", 'W', "baguette");
stones[7] = new Diamond( "E6393", 2.3, "VS2", 'I', "brilliant");
stones[8] = new Diamond( "C5619", 2.8, "VVS1", 'E', "pear");
stones[9] = new Diamond( "E8348", 1.4, "VS2", 'G', "brilliant");
stones[10] = new Diamond( "D2381", 1.7, "I3", 'G', "brilliant");
stones[11] = new Diamond( "C9253", 1.3, "VS2", 'H', "baguette");
stones[12] = new Diamond( "G3459", 2.1, "VS2", 'H', "rose");
stones[13] = new Diamond( "B3598", 2.4, "VVS2", 'D', "pear");
stones[14] = new Diamond( "D9836", 2.8, "IF", 'E', "princess");
stones[15] = new Diamond( "E1046", 2.2, "FL", 'E', "rose");
Arrays.sort( stones );
for ( int j=0; j<stones.length; j++ )
System.out.println( stones[j].toString() );
}
}
在與多個參數進行比較時,我們應該最后返回0並繼續比較優先級的參數。 以下是按字數,顏色和清晰度排序的代碼。
您可以根據需要在顏色和清晰度之間添加更多條件。
public int compareTo(Crawford_Diamond other) {
if (getCarot() < other.getCarot()) {
return 1;
} else if (getCarot() > other.getCarot()) {
return -1;
}
if (this.color < other.getColor()) {
return 1;
} else if (this.color > other.getColor()) {
return -1;
}
if (this.clarity.compareTo(other.getClarity())<1) {
return 1;
} else if (this.clarity.compareTo(other.getClarity())>1) {
return -1;
}
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.