Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/372.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何将对象与另一个对象进行比较_Java - Fatal编程技术网

Java 如何将对象与另一个对象进行比较

Java 如何将对象与另一个对象进行比较,java,Java,我运行以下命令 Choice choice1 = new Choice(0); Choice choice2 = new Choice(1); int result = choice1.compareWith(choice2); IO.outputln("Actual: " + result); 比较法 public int compareWith(Choice anotherChoice) { int result=0;

我运行以下命令

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

       IO.outputln("Actual: " + result);
比较法

public int compareWith(Choice anotherChoice)
    {

        int result=0;           
        if (anotherChoice==0||type==0)
            result=1;
        if (anotherChoice==1&&type==1)
        result=-11;
    }
程序说我不能将另一个选项(选项类)与整数进行比较。我该怎么做呢

if (anotherChoice==0||type==0)
由于
另一个选择
是一个对象,您无法直接与
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;
    }

您应该为此实施
Comparable
。在比较值时,还需要从选项中选择
类型
值:

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;
    }
}
公共类选择实现了可比较的
{
@凌驾
公共整数比较(选择该选项)
{
int结果=0;
if(anotherChoice.type==0 | | type==0)
结果=1;
if(anotherChoice.type==1&&type==1)
result=-11;//可能应该是-1
返回结果;
}
}

如错误所述,另一个选项的类型为
Choice
。我假设您想要比较实例变量
类型
。所以它应该是另一个选择.type==this.type