// Test out the Complex class with a couple of hardcoded numbers // // File: ComplexTest.java // Author: Benjamin Lewis // Last modified: Tuesday February 23, 1999 public class ComplexTest { public static void main(String[] args) { Complex c1 = new Complex(4.5, 2.3); Complex c2 = new Complex(1.1, 7.7); System.out.println("c1:\t"+c1); System.out.println("c2:\t"+c2); System.out.println("c1+c2:\t"+Complex.add(c1,c2)); System.out.println("c1-c2:\t"+Complex.subtract(c1,c2)); System.out.println("c1*c2:\t"+Complex.multiply(c1,c2)); } } ---------------------------------------------------------- // This class implements complex numbers. Static methods for adding, // subtracting, and multiplying two complex numbers are provided. // Double precision floating point numbers are used for the real and // imaginary parts. // // File: Complex.java // Author: Benjamin Lewis // Last modified: Tuesday February 23, 1999 public class Complex { private double real = 0; private double imag = 0; public Complex() { } public Complex(double real, double imag) { this.real = real; this.imag = imag; } public static Complex add(Complex c1, Complex c2) { return new Complex(c1.real+c2.real, c1.imag+c2.imag); } public static Complex subtract(Complex c1, Complex c2) { return new Complex(c1.real-c2.real, c1.imag-c2.imag); } public static Complex multiply(Complex c1, Complex c2) { // (a+bi)*(c+di) = (ac-bd) + (ad+bc)i double real = c1.real*c2.real - c1.imag*c2.imag; double imag = c1.real*c2.imag + c1.imag*c2.real; return new Complex(real, imag); } public String toString() { // this is actually nicer than providing a "print" method. return new String("" + real + " + " + imag + "*i"); } public void print() { // toString has been defined System.out.println(this); } // Accessor methods (not required) public double getRealPart() { return real; } public double getImaginaryPart() { return imag; } public void setRealPart(double real) { this.real = real; } public void setImaginaryPart(double real) { this.real = real; } }