// Copyright (c) 2001

package Imaginary;

/**
 * Imaginary.Complex
 * 

* @author Michael A. Elms * Complex Numbers are written in the form a+bi */ public class Complex { int a; int b; /** * Constructor */ public Complex(int a) { this.a = a; this.b = 0; } public Complex(int a, int b) { this.a = a; this.b = b; } public void printComplex(Complex c) { System.out.println("printComplex"); if (c.a != 0) { if (c.b > 0) System.out.println(c.a + " + " + c.b + "i"); else if (c.b == 0) System.out.println(c.a); else System.out.println(c.a + " + (" + c.b + "i)"); } else System.out.println(c.b + "i"); } public String toString(Complex c) { String temp; if (c.a != 0) { if (c.b > 0) temp = c.a + " + " + c.b + "i"; else if (c.b == 0) temp = c.a + ""; else temp = c.a + " + (" + c.b + "i)"; } else temp = c.b + "i"; temp = "(" + temp + ")"; return temp; } public Complex addComplex(Complex num1, Complex num2) { System.out.println("addComplex"); Complex result = new Complex(0, 0); System.out.println("I want to add " + num1.toString(num1) + " to " + num2.toString(num2)); result.a = num1.a + num2.a; result.b = num1.b + num2.b; System.out.println("The result is " + result.toString(result)); return result; } /** * main * @param args */ public static void main(String[] args) { System.out.println("Main"); Complex complex = new Complex(1, 2); complex.printComplex(complex); Complex c1 = new Complex(1, 2); Complex c2 = new Complex(4, 0); Complex c3 = new Complex(1,-2); Complex c4 = new Complex(10); Complex c5 = new Complex(0, -10); c1.printComplex(c1); c2.printComplex(c2); c3.printComplex(c3); c4.printComplex(c4); c5.printComplex(c5); complex.addComplex(c1, c2); complex.addComplex(c1, c3); } } RESULTS: Main printComplex 1 + 2i printComplex 1 + 2i printComplex 4 printComplex 1 + (-2i) printComplex 10 printComplex -10i addComplex I want to add (1 + 2i) to (4) The result is (5 + 2i) addComplex I want to add (1 + 2i) to (1 + (-2i)) The result is (2)