2013-11-09 2 views
0

Я пытаюсь ранжировать/сортировать алмазы по размеру карата. Если размер равен, то я хочу ранжировать их либо цветом, либо ясностью, в зависимости от того, что дает лучший рейтинг. Я не могу заставить его работать правильно. Она работает, но это будет только ранжировать их в соответствии с размером каратаИспользование сопоставимого интерфейса для сортировки по массиву

Crawford_Diamond[] stones = new Crawford_Diamond[16]; 

stones[0] = new Crawford_Diamond("A1023", 1.0, "VS1", 'F', "brilliant"); 
stones[1] = new Crawford_Diamond("A5911", 1.1, "VVS2", 'G', "rose"); 
stones[2] = new Crawford_Diamond("C5427", 1.0, "VS1", 'D', "princess"); 
stones[3] = new Crawford_Diamond("D8307", 1.6, "SI1", 'H', "brilliant"); 
stones[4] = new Crawford_Diamond("B4825", 0.3, "I1", 'D', "rose"); 
stones[5] = new Crawford_Diamond("A1844", 2.1, "VS2", 'D', "lozenge"); 
stones[6] = new Crawford_Diamond("A3747", 3.1, "SI2", 'W', "baguette"); 
stones[7] = new Crawford_Diamond("E6393", 2.3, "VS2", 'I', "brilliant"); 
stones[8] = new Crawford_Diamond("C5619", 2.8, "VVS1", 'E', "pear"); 
stones[9] = new Crawford_Diamond("E8348", 1.4, "VS2", 'G', "brilliant"); 
stones[10] = new Crawford_Diamond("D2381", 1.7, "I3", 'G', "brilliant"); 
stones[11] = new Crawford_Diamond("C9253", 1.3, "VS2", 'H', "baguette"); 
stones[12] = new Crawford_Diamond("G3459", 2.1, "VS2", 'H', "rose"); 
stones[13] = new Crawford_Diamond("B3598", 2.4, "VVS2", 'D', "pear"); 
stones[14] = new Crawford_Diamond("D9836", 2.8, "IF", 'E', "princess"); 
stones[15] = new Crawford_Diamond("E1046", 2.2, "FL", 'E', "rose"); 

Arrays.sort(stones); 

for (int j=0; j<stones.length; j++) 
    System.out.println(stones[j].toString()); 
public class Crawford_Diamond implements Comparable<Crawford_Diamond> 
{ 

private String stockNumber; //diamond stock number 
private double carot; //carrot size 
private String clarity; 
private char color; //color of the diamond. D=Best Z=Worst 
private String cut; //cut of the diamond 
private int diamondColor; 
private int diamondClarity; 

public Crawford_Diamond(String sN, double car, String clar, char col, String cutType) 
{ 
    stockNumber = sN; 
    carot = car; 
    clarity = clar; 
    color = col; 
    cut = cutType; 

} 
//gets the stock number of the diamond 
public String getStock(){return stockNumber; } 

//gets the carrot 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;} 
public int compareClarity(String getClarity) 
{ 
    int diamondClarity=0; 
    if (getClarity.equals("Fl")) 
     diamondClarity = 10; 
    else if (getClarity.equals("IF")) 
     diamondClarity = 9; 
    else if (getClarity.equals("VVS1")) 
     diamondClarity = 8; 
    else if (getClarity.equals("VVS2")) 
     diamondClarity = 7; 
    else if (getClarity.equals("VS1")) 
     diamondClarity = 6; 
    else if (getClarity.equals("VS2")) 
     diamondClarity = 5; 
    else if (getClarity.equals("SI1")) 
     diamondClarity = 4; 
    else if (getClarity.equals("SI2")) 
     diamondClarity = 3; 
    else if (getClarity.equals("I1")) 
     diamondClarity = 2; 
    else if (getClarity.equals("I2")) 
     diamondClarity = 1; 
    else if (getClarity.equals("I3")) 
     diamondClarity = 0; 
    return diamondClarity; 
} 

public int getRankD1() 
{ 
int rankD1=0; 
if (this.diamondColor > this.diamondClarity) 
    rankD1 = diamondColor; 
else if (this.diamondColor < this.diamondClarity) 
    rankD1 = diamondClarity; 
return rankD1; 
} 
public int getRankD2() 
{ 
int rankD2=0; 
if (this.diamondColor > this.diamondClarity) 
rankD2 = diamondColor; 
else if (this.diamondColor < this.diamondClarity) 
rankD2 = diamondClarity; 
return rankD2; 
} 

public int compareColor(char getColor) 
{ 
    int diamondColor=0; 
    if (getColor=='D' || getColor=='E') 
     diamondColor = 10; 
    else if (getColor=='F' || getColor=='G') 
     diamondColor = 9; 
    else if (getColor=='H' || getColor=='I') 
     diamondColor = 8; 
    else if (getColor=='J' || getColor=='K') 
     diamondColor = 7; 
    else if (getColor=='L' || getColor=='M') 
     diamondColor = 6; 
    else if (getColor=='N' || getColor=='O') 
     diamondColor = 5; 
    else if (getColor=='P' || getColor=='Q') 
     diamondColor = 4; 
    else if (getColor=='R' || getColor=='S') 
     diamondColor = 3; 
    else if (getColor=='T' || getColor=='U') 
     diamondColor = 2; 
    else if (getColor=='V' || getColor=='W') 
     diamondColor = 1; 
    else if (getColor=='X' || getColor=='Y') 
     diamondColor = 0; 
    return diamondColor; 
} 

public int compareTo(Crawford_Diamond other) 
{ 

    if (this.carot > other.getCarot()) 
    { 
     return -1; 
    } 
    else if (this.carot < other.getCarot()) 
    { 
     return 1; 

    } 
    else if(this.getRankD1() > other.getRankD2()) 
    { 
     return -1; 
    } 
    else if(this.getRankD1() < other.getRankD2()) 
    { 
     return 1; 
    } 
    else 
     return 0;} 



public String toString() 
{ 
    return "{stockNumber :: " +getStock() + " carot :: " +getCarot() + " clarity :: " +getClarity()+ " color :: " +getColor() + " cut :: " +getCut()+"}"; 
} 
} 
+3

Вы действительно должны использовать 'enum' вместо строк для поля' clearity'; это проще и безопаснее, и вы можете устранить весь «переключатель». – chrylis

+0

Используйте специализированные компараторы, если вам нужно отсортировать объекты несколькими способами. – mre

ответ

0

Вы почти правы. Если вы просто добавите две строки в свой конструктор, ваш код будет делать именно то, что вы хотите.

public Crawford_Diamond(String sN, double car, String clar, char col, String cutType) 
{ 
    stockNumber = sN; 
    carot = car; 
    clarity = clar; 
    color = col; 
    cut = cutType; 

    diamondColor = compareColor(color); 
    diamondClarity = compareClarity(clarity); 
} 

Есть и другие вещи, которые вы можете сделать, чтобы очистить свой код. Вы делаете переименование compareClarity в getClarityValue, так как вы просто переводите строку в целое число. То же самое касается цвета.

Вам также не нужны две версии метода ранжирования. Поскольку метод всегда вызывается на данном алмазном объекте, один метод getRank() будет работать только отлично вместо getRankD1() и getRankD2().

+0

большое спасибо. Теперь он отлично работает и выглядит немного чище. –

0

попробовать нормально, как они двойники не Интс ...

public int compareTo(Crawford_Diamond other) 
{ 
    int value = 0; 
    if (this.carot > other.getCarot()) 
    { 
     value = -1; 
    } 
    else if (this.carot < other.getCarot()) 
    { 
     value = 1; 
    }  
    if (value == 0){ 
     value = getRankD1() - other.getRankD1();   
    } 
    return value; 
} 
+0

Ваш код не компилируется. Он возвращает 'double' вместо' int'. –

0

В подобных случаях я считаю, что проще дают значения абсолютного балла ....

во-первых, я хотел бы изменить свои функции, возвращать значения в обратном порядке (где цвет D имеет оценку 0, а цвет X имеет балл 10. Кроме того, лучшая ясность ('fl' уже t он высокий счет ....).

Используйте оценки, которые оценивают самый лучший атрибут. У вас есть шкала от 0 до 10.

Итак, я бы метод на Crawford_Diamond под названием getScore(), который будет делать:

public int getScore() { 
    int score = (int)(carat * 100000); // carat of 2.2 will become 220000 
    int colorscore = getColorScore(color); 
    int clarityscore = getClarityScore(clarity); 
    if (color > clarity) { 
     // color of D is best, give it score 1000 and add the clarity score 
     score = score + (100 * color) + clarity; 
    } else { 
     score = score + (100 * clarity) + color; 
    } 
    return score; 
} 

Затем ваш метод CompareTo становится просто:

public int compareTo(Crawford_Diamond other) { 
    return other.getScore() - getScore(); 
} 

(обратите внимание, это карат, а не каротин (или карет))

Смежные вопросы