0

我收到错误:

java.lang.AssertionError: expected: learning.java.advancedoop2.MyComplex<(2.0+10.0i)> but was: learning.java.advancedoop2.MyComplex<(2.0+10.0i)>
Expected :learning.java.advancedoop2.MyComplex<(2.0+10.0i)> 
Actual   :learning.java.advancedoop2.MyComplex<(2.0+10.0i)>

我现在正在研究 MyComplex 类,如 3.1 所示:http: //www.ntu.edu.sg/home/ehchua/programming/java/J3f_OOPExercises.html#zz-2

这是相关的代码的一部分:

package learning.java.advancedoop2;

public class MyComplex {

    private double real = 0.0;
    private double imag = 0.0;

public MyComplex() {

}

    public MyComplex add(MyComplex right) {
        this.imag += right.imag;
        this.real += right.real;
        return this;
    }
}

我试图进行测试,当我运行它们时,我遇到的错误是向上的,这是我的测试代码的一部分:

@Test
public void add() {

    MyComplex myComplexFirst = new MyComplex(1, 5);
    MyComplex myComplexSecond = new MyComplex(1, 5);
    MyComplex myComplexThird = new MyComplex(myComplexFirst.getReal() + myComplexSecond.getReal(), myComplexFirst.getImag() + myComplexSecond.getImag());
    myComplexFirst.add(myComplexSecond);
    MyComplex newComplex = myComplexFirst;
    assertEquals(newComplex, myComplexThird);
}
4

2 回答 2

2

您是否覆盖了自定义类中的 equals 方法?

如果您不这样做,则默认行为是比较参考。这将解释您收到的错误消息。

这是令人困惑的,因为您已经覆盖了 toString 方法,该方法显示两个实例具有相同的值。

于 2019-07-01T05:42:50.457 回答
0

您需要重写 equals 方法,以便 java 知道如何比较两个MyComplex对象。现在它不知道您要根据realimag值比较对象。

@Override
public boolean equals(Object o) { 

    // If the object is compared with itself then return true   
    if (o == this) { 
        return true; 
    } 

    // Check if o is an instance of MyComplex
    if (!(o instanceof MyComplex)) { 
        return false; 
    } 

    // typecast o to MyComplex so that we can compare data members  
    MyComplex c = (MyComplex) o; 

    // Compare the data members and return accordingly  
    return Double.compare(real, c.getReal()) == 0
            && Double.compare(imag, c.getImag()) == 0; 
} 
于 2019-07-01T07:32:04.867 回答