AssertionError - imaginary and real numbers adder

85 views Asked by At

I'm getting error:

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)>

I'm now working on MyComplex Class like shown on 3.1: http://www.ntu.edu.sg/home/ehchua/programming/java/J3f_OOPExercises.html#zz-2

Here's a part of the code that's relevant:

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;
    }
}

I tried to make tests, and when I ran them, error that I've got is upside, here's part of my test code:

@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);
}
2

There are 2 answers

0
Patrick On

Did you override the equals method in your custom class ?

If you didn't, the default behavior is to compare the references. That would explain the error message you get.

It is confusing because you have overriden the toString method which displays both instances to have the same values.

0
Mirko Brandt On

You need to override the equals method so that java knows how to compare two MyComplex Objects. Right now it doesn't know that you want to compare the objects based on the real and imag values.

@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; 
}