0

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);
}
Ziemek
  • 1
  • 2
  • 2
    you need to implement the `equals` method to let java know when to different objects containing the same values are actually considered equal – njzk2 Jul 01 '19 at 05:34
  • 3
    The class code you show us can't be complete. Otherwise, the output in the error message would be different (it would not show the numbers!). – jokster Jul 01 '19 at 05:47
  • @jokster that may be why Ziemek wrote "Here's a part of the code that's relevant". – Dawood ibn Kareem Jul 01 '19 at 06:43

2 Answers2

2

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.

Patrick
  • 1,458
  • 13
  • 27
0

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; 
} 
Mirko Brandt
  • 455
  • 3
  • 8