/** * Author: Josiah Yoder et al. * User: yoder * Class: SE1011-011 * Lesson: Week 8, Day 1 */ public class Complex051_10_1 { // From Thursday (Week 9, Day 3) private static int numInstances = 0; // 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_10_1() { // New way this(0.0, 0.0); // Old way // real = 0; // imaginary = 0; } public Complex051_10_1(double real, double imaginary) { this.real = real; this.imaginary = imaginary; } public Complex051_10_1(double real) { this.real = real; imaginary = 0; } public Complex051_10_1(Complex051_10_1 old) { this.real = old.real; this.imaginary = old.imaginary; } // From main: // Complex051_10_1 c1 = new Complex051_10_1(3,4); // Complex051_10_1 c2 = new Complex051_10_1(1,2); // c1 = c1.add(c2); // += public Complex051_10_1 add(Complex051_10_1 other) { // this; // reference to this object // other; // reference to the other object Complex051_10_1 result = new Complex051_10_1(); // ERROR! this.real = this.real + other.real; this.imaginary = this.imaginary + other.imaginary; return result; } public Complex051_10_1 add(double real) { Complex051_10_1 result = new Complex051_10_1(); 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_10_1 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; } }