summary refs log blame commit diff stats
path: root/java/code/ComplexCalculations.java
blob: 5ce056fca3a7b0c9efa0e21e15955c1ad5390ff2 (plain) (tree)










































                                                                                             
import java.util.Scanner;
import java.util.InputMismatchException;

class Complex {
    double real, imag;
    Complex(double r, double i) {
        real = r;
        imag = i;
    }
    @Override
    public String toString() {
        return real + (imag > 0.0 ? " + " : " - ") + Math.abs(imag) + "i";
    }
}

class ComplexOperations {
    static Complex add(Complex a, Complex b) {
        return new Complex(a.real + b.real, a.imag + b.imag);
    }
}

class ComplexCalculations {
    static Complex takeComplexInput() {
        var sc = new Scanner(System.in);
        System.out.print("  Enter real part: ");
        var real = sc.nextDouble();
        System.out.print("  Enter imaginary part: ");
        var imaginary = sc.nextDouble();
        return new Complex(real, imaginary);
    }
    public static void main(String args[]) {
        try {
            System.out.println("First complex number:-");
            var x = takeComplexInput();
            System.out.println("Second complex number:-");
            var y = takeComplexInput();
            System.out.println("(" + x + ") + (" + y + ") = " + ComplexOperations.add(x, y));
        } catch (InputMismatchException e) {
            System.err.println("Invalid number given as input");
        }
    }
}