// Complex numbers package homework1b; import java.io.*; import java.util.*; public class Complex { private double re, im; // constructors public Complex() { re = 0.0; im = 0.0; } public Complex(double re) { this.re = re; im = 0.0; } public Complex(double re, double im) { this.re = re; this.im = im; } public Complex add(Complex z2) { Complex temp = new Complex(); temp.re = re + z2.re; temp.im = im + z2.im; return temp; } public Complex sub(Complex z2) { Complex temp = new Complex(); temp.re = re - z2.re; temp.im = im - z2.im; return temp; } public Complex mul(Complex z2) { Complex temp = new Complex(); temp.re = re*z2.re - im*z2.im; temp.im = im*z2.re + re*z2.im; return temp; } public Complex div(Complex z2) throws ArithmeticException { Complex temp = new Complex(); double den = z2.re*z2.re + z2.im*z2.im; if (den == 0.0) throw new ArithmeticException(); temp.re = (re*z2.re + im*z2.im)/den; temp.im = (im*z2.re - re*z2.im)/den; return temp; } public String toString() { return "(" + re + "," + im + ")"; } public double Re(Complex z) { return re; } public double Im(Complex z) { return im; } public Complex Conj() { Complex temp = new Complex(); temp.re = re; temp.im = -im; return temp; } public boolean equals(Object rhs) { if (! (rhs instanceof Complex)) return false; Complex z = (Complex) rhs; return z.re == re && z.im == im; } public void readFromKeyboard() { BufferedReader in = new BufferedReader( new InputStreamReader( System.in )); String line; StringTokenizer str; System.out.println("Enter complex number in format (a,b): "); try { line = in.readLine(); str = new StringTokenizer( line, " ()," ); if (str.countTokens() != 2) throw new NumberFormatException(); re = Double.parseDouble(str.nextToken() ); im = Double.parseDouble(str.nextToken() ); } catch (Exception e) { System.err.println("Error: need a complex number " + "in format (a,b)"); } } }