Complete the ComplexNumber class we began in the past week's lectures, according to the UML Class diagram shown below. Note that you need to implement a new static method that computes the magnitude of a ComplexNumber (recall from you math courses that the magnitude of a complex number is simply the square root of the sum of the squares of the real and imaginary components).
Use the following driver class to verify that your
ComplexNumber is implemented correctly:
/** * This program creates and manipulates ComplexNumbers */ package msoe.se1011.complexdriver; import msoe.se1011.complex.ComplexNumber; /** * @author hornick * Driver/main class */ public class ComplexDriverHW { /** * @param args */ public static void main(String[] args) { ComplexNumber x1 = new ComplexNumber(1,2); ComplexNumber x2 = x1.add(0,0); // x2 = (1,2) // Print the values, via automatic invocation of the over-ridden toString() method System.out.println( "x1 =" + x1); System.out.println( "x2 = " + x2 ); if( x1.equals(x2) ) { // do x1 and x1 represent the same number? System.out.println( "x1 and x2 are numerically equal."); } else { // x1 and x2 are not equal System.out.println( "x1 and x2 are NOT numerically equal."); } ComplexNumber sum = x1.add(1,1); // sum = (2,3), x1 still= (1,2) x2 = x2.add(x1); // x2 = (2,4); x2 is reassigned to the new ComplexNumber System.out.println( "sum = " + sum ); System.out.println( "x2 = " + x2 ); x2 = x1; // what is happening here?? if( x1 == x2 ) { // do x1 and x1 reference the same object now? System.out.println( "After x2=x1, x1 and x2 are the same object."); } else { // x1 and x2 are not equal System.out.println( "After x2=x1, x1 and x2 are NOT the same object."); } double magnitude = ComplexNumber.mag(x1); // compute magnitude // Note the format specifier: System.out.printf( "Magnitude of x1 = %#.3f \n",magnitude ); magnitude = ComplexNumber.mag(x2); System.out.printf( "Magnitude of x2 = %#.3f \n",magnitude ); magnitude = ComplexNumber.mag(sum); System.out.printf( "Magnitude of sum = %#.3f\n ",magnitude ); } }
When you run this program, you should get the following output in the console:
x1 =[1.0,2.0] x2 = [1.0,2.0] x1 and x2 are numerically equal. sum = [2.0,3.0] x2 = [2.0,4.0] After x2=x1, x1 and x2 are the same object. Magnitude of x1 = 2.236 Magnitude of x2 = 2.236 Magnitude of sum = 3.606