2012-05-01 3 views
1

Мне сказали, что compareTo должен вернуть int ... not Boolean.
Например:
compareTo: как вернуть логическое значение?

Возвращает

0, если равно б
-1, если < б
+1, если а> Ь

Я немного смущен этим. Любая помощь будет принята с благодарностью.

public int compareTo(Cheese anotherCheese) 
    throws ClassCastException 
    { 
     if (!(anotherCheese instanceof Cheese)) 
      throw new ClassCastException("A Cheese object expected."); 

     if(getCheeseType().compareTo(anotherCheese.getCheeseType())) 
      return -1; 
     else if (getCheeseType().compareTo(anotherCheese.getCheeseType())) 
      return 1; 
     else 
      return cheesePrice > anotherCheese.getCheesePrice(); 
    } 

Когда я компилирую, я получаю сообщение об ошибке сказав:


несовместимые типы
if(getCheeseType().compareTo(anotherCheese.getCheeseType()))
несовместимые типы
else if (getCheeseType().compareTo(anotherCheese.getCheeseType()))
несовместимые типы
return cheesePrice > anotherCheese.getCheesePrice();

ответ

4

compareTo действительно возвращает int, а не boolean. Из-за этого вы получаете ошибки компиляции. Внутри заявления if вы должны поставить boolean.

Таким образом, вместо

if(getCheeseType().compareTo(anotherCheese.getCheeseType()))

написать

if(getCheeseType().compareTo(anotherCheese.getCheeseType()) < 0)

0

вобще

return getCheeseType().compareTo(anotherCheese.getCheeseType()); 

, если вы также хотите сравнить по цене, то сделать

if(getCheeseType().compareTo(anotherCheese.getCheeseType())!=0) 
    return getCheeseType().compareTo(anotherCheese.getCheeseType()); 
//cheeseTypes are equal 
if(cheesePrice < anotherCheese.getCheesePrice()) 
    return -1; 
else if (cheesePrice > anotherCheese.getCheesePrice()) 
    return 1; 
else 
    return 0; 
0
// Order by type. 
    int delta = getCheeseType().compareTo(anotherCheese.getCheeseType()); 
    if (delta != 0) { return delta; } 
    // If of the same type, order by price. 
    if (cheesePrice < anotherCheese.getCheesePrice()) { return -1; } 
    if (cheesePrice > anotherCheese.getCheesePrice()) { return 1; } 
    return 0; 
0

Да compareTo метод возвращает тип INT, а не boolean. Но вы используете getCheeseType().compareTo(anotherCheese.getCheeseType()) в цикле if, что приведет к ошибкам компиляции времени. измените это.

public int compareTo(Cheese anotherCheese) 
    throws ClassCastException 
    { 
     if (!(anotherCheese instanceof Cheese)) 
      throw new ClassCastException("A Cheese object expected."); 

     else return getCheeseType().compareTo(anotherCheese.getCheeseType())) 

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