/** * Author: Josiah Yoder et al. * User: yoder * Class: SE1011-011 * Lesson: Week 8, Day 1 */ public class Complex051_9_3 { // EDIT private static int numInstances = 0; // END EDIT // The complex number is // real + imaginary * i // where i is sqrt(-1) private double real; private double imaginary; // CLASS CONSTANT: // use "static" keyword public static final double MY_CONSTANT = 5.0; public Complex051_9_3() { // New way this(0.0, 0.0); // Old way // real = 0; // imaginary = 0; } public Complex051_9_3(double real, double imaginary) { this.real = real; this.imaginary = imaginary; } public Complex051_9_3(double real) { this.real = real; imaginary = 0; } public Complex051_9_3(Complex051_9_3 old) { this.real = old.real; this.imaginary = old.imaginary; } // From main: // Complex051_9_3 c1 = new Complex051_9_3(3,4); // Complex051_9_3 c2 = new Complex051_9_3(1,2); // c1 = c1.add(c2); // += public Complex051_9_3 add(Complex051_9_3 other) { // this; // reference to this object // other; // reference to the other object Complex051_9_3 result = new Complex051_9_3(); // ERROR! this.real = this.real + other.real; this.imaginary = this.imaginary + other.imaginary; return result; } public Complex051_9_3 add(double real) { Complex051_9_3 result = new Complex051_9_3(); result.real = this.real + real; result.imaginary = this.imaginary; return result; } // // Treat complex number as a vector // and return the magnitude. // // That is, we want to find the length // of the vector from the origin // to the complex number // when plotted on a graph. public double magnitude() { // sqrt(x^2 + y^2) // sqrt(real^2 + imaginary^2) return Math.sqrt(real*real+imaginary*imaginary); } /// Back to Chapter 7 public void swap(Complex051_9_3 other) { //other.real; //this.real; double real; double imaginary; real = this.real; imaginary = this.imaginary; this.real = other.real; this.imaginary = other.imaginary; other.real = real; other.imaginary = imaginary; // Other good ideas: // other.real = this.real; } }