I am doing a very basic Complex Numbers class in Java but when I test my add and multiply functions I don't get the results I expect. I don't understand what is wrong or how to fix it.
When I run the program I get the following output:
a+b: ComplexNumber@1540e19d
a*b: ComplexNumber@677327b6
I should get the proper addition and multiplication of two complex numbers (following the rules of complex numbers of course)
Any help would be much appreciated! Thanks in advance.
Here is the code:
public class ComplexNumber {
private double real;
private double imaginary;
public ComplexNumber(double r, double i) {
real = r;
imaginary = i;
}
public double real() {
return real;
}
public double imaginary() {
return imaginary;
}
public ComplexNumber add(ComplexNumber c) {
double newr = real + c.real();
double newi = imaginary + c.imaginary();
return new ComplexNumber(newr, newi);
}
public ComplexNumber multiply(ComplexNumber c) {
double newr = real*c.real() - imaginary*c.imaginary();
double newi = real*c.imaginary() + imaginary*c.real();
return new ComplexNumber(newr, newi);
}
public static void main(String[] args) {
ComplexNumber c1 = new ComplexNumber(1.0, 2.0);
ComplexNumber c2 = new ComplexNumber(-1.0, 0.5);
String c1plusc2 = c1.add(c2).toString();
String c1timesc2 = c1.multiply(c2).toString();
System.out.println("a+b :" + c1plusc2);
System.out.println("a*b :" + c1timesc2);
}
}