2017-08-03 42 views
1

我運行下面的我如何比較對象與另一個對象

Choice choice1 = new Choice(0); 
     Choice choice2 = new Choice(1); 
     int result = choice1.compareWith(choice2); 

     IO.outputln("Actual: " + result); 

的compareWith方法

public int compareWith(Choice anotherChoice) 
    { 

     int result=0;   
     if (anotherChoice==0||type==0) 
      result=1; 
     if (anotherChoice==1&&type==1) 
     result=-11; 
    } 

節目中說,我不能比較一個整數anotherchoice(選擇類)。我該怎麼做。

+0

的錯誤說,anotherchoice的類型爲'Choice'。我假設你想比較實例變量'type'。所以它應該是'anotherChoice.type == this.type' – sidgate

回答

2
if (anotherChoice==0||type==0) 

由於anotherChoice是一個對象,你不能直接與0比較。您應該實際檢查該對象的字段。所以你的代碼應該是

if (anotherChoice.type==0|| this.type==0) 

其他條件相同。

另一個錯誤是你沒有從你的方法中返回任何東西。你應該。

public int compareWith(Choice anotherChoice) 
    { 

     int result=0;   
     if (anotherChoice==0||type==0) 
      result=1; 
     if (anotherChoice==1&&type==1) 
     result=-11; 

     return result; 
    } 
1

您應該爲此執行Comparable。你也應該需要得到type值了,當你比較值的選擇:

public class Choice implements Comparable<Choice> 
{ 
    @Override 
    public int compareTo(Choice that) 
    { 
     int result = 0; 
     if (anotherChoice.type == 0 || type == 0) 
      result = 1; 
     if (anotherChoice.type == 1 && type == 1) 
      result = -11; // should probably be -1 

     return result; 
    } 
}