2017-08-03 119 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; 
    } 
}