package class7_3_Complex; /** * A complex number. * * This number consists of two parts, the real part * (an ordinary number with a decimal part) * and the imaginary part (an ordinary number * multiplied by sqrt(-1). * * The full number is * real + imag * i * * where i = sqrt(-1) */ public class Complex { private double real; private double imag; /** * Create a complex zero. * Both real and imaginary parts are zero */ public Complex() { this(0,0); // DIFFERENT FROM: new Complex(0,0) <- DOESN'T WORK } /** * Create a real number. The imaginary part is zero. * @param real The value of the real number */ public Complex(double real) { // Exercise: ??? What goes here ??? } /** * Create a complex number * @param real The real part of the number * @param imag The imaginary part of the number */ public Complex(double real, double imag) { this.real = real; this.imag = imag; } /** * Multiply this complex number by the other one. * @param other The other complex number to multiply by. Must not be null. * @return a new complex object holding the result */ public Complex multBy(Complex other) { Complex result = new Complex(); result.real = this.real * other.real - this.imag * other.imag; result.imag = this.real * other.imag + this.imag * other.real; return result; } /** * @return This number, formatted similar to "4.5 + 3.4 i" */ public String toString() { // Exercise: Print 4.0 i as 4 i instead of 0.0 + 4.0i return real + " + " + imag + "i"; } }