package ClassesIntro;


public class ComplexNumber {

    private double real;
    private double imaginary;

    /* Constructor for complex numbers.  A complex number MUST have a real
     * part and an imaginary part.
     */
    public ComplexNumber(double initReal, double initIm) {
        setReal(initReal);
        setImaginary(initIm);
    }

    /* Code to "multiply" two complex numbers.  This is necessary, since Java
     * knows nothing about complex numbers, so the programmer must define this
     * operation.
     */
    public ComplexNumber multiply(ComplexNumber otherNumber) {
        // The formula: (a + bi) * (c + di) = (ac - bd) + (ad + bc)i.
        double a = this.real;
        double b = this.imaginary;
        double c = otherNumber.real;
        double d = otherNumber.imaginary;

        double nReal = a * c - b * d;
        double nImaginary = a * d + b * c;

        // This is the key... return a NEW complex number using the results of the formula.
        return new ComplexNumber(nReal, nImaginary);
    }

    /***** Java knows to use the toString() method when printing objects *****/
    @Override
    public String toString() {
        String formatted;
        double r = Math.round(this.real * 100000) / 100000.0;
        double i = Math.round(this.imaginary * 100000) / 100000.0;

        if (i > 0)
            formatted = r + "+" + i + "i";
        else if (imaginary < 0)
            formatted = r + "" + i + "i";
        else {
            formatted = Double.toString(r);
        }

        return "(" + formatted + ")";
    }

    /***** Public methods which expose private fields. *****/
    public double getReal() {
        return this.real;
    }

    public double getImaginary() {
        return this.imaginary;
    }

    public void setReal(double newReal) {
        this.real = newReal;
    }

    public void setImaginary(double newIm) {
        this.imaginary = newIm;
    }
}