Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

EGR 140: Computer Programming Assignment # 13 : Write an error-free Java program

ID: 3812745 • Letter: E

Question

EGR 140: Computer Programming

Assignment # 13:

Write an error-free Java program to do the following things.

Write a class called “Complex”. The class has two private data members which correspond to the real and imaginary parts of a complex number.

The class Complex should have several (methods) functions: set the values, display the number in real/imaginary (re + j*im) format, and display the number in polar (r, theta) format.

The main program should declare two objects of type Complex. It should set the first object to 4 + j3 and the second object to 1.5-j5.5.

The program should set object 2 to the sum of object 1 and object 2. That is, the real component of object 2 should be set to object1.re +object2.re and similarly for the imaginary part of object 2. You should use a method like add() or plus().

The main program should then print object 2 in a polar format (with theta in degrees) and object 1 in Cartesian format. Good programming design is to make your objects and methods general in order to be used in multiple contexts. Thus, write your code so that the println() statements are in the main() module and it calls method(s) for object1 and object2 to access the data.

Output:

MM§MThe complex numbers are:
MM§Mobject 2: length = 6.041522986797286 th = -24.443954780416536
MM§Mobject 1 = 4.0 + i3.0

Explanation / Answer

import java.util.*;

class Complex {

private double re; // the real part

private double im; // the imaginary part

// create a new object with the given real and imaginary parts

public Complex(double real, double imag) {

re = real;

im = imag;

}

public void setReal(double _re){

re=_re;}

public void setImgnry(double _img){

im=_img;}

public double getReal(){

return re;}

public double getImgnry(){

return im;}

// return a string representation of the invoking Complex object

public String display() {

if (im == 0) return re + "";

if (re == 0) return im + "i";

if (im < 0) return re + " - " + (-im) + "i";

return re + " + i" + im ;

}

public Complex add(Complex obj){

double sum_re= obj.re+this.re;

double sum_im=obj.im+this.im;

return new Complex(sum_re,sum_im);}

public String toPolar(){

double length = Math.sqrt(Math.pow(this.re, 2) + Math.pow(this.im, 2));

double angles = Math.atan2(this.im,this.re);

return "length = "+length+" th= "+angles*(180/Math.PI); //return polar form

}

public static void main(String args[]){

Complex obj1=new Complex(4,3); //create objects

Complex obj2=new Complex(1.5,-5.5);

obj2=obj1.add(obj2); //add and store in obj2

System.out.println("The complex numbers are .Object2: "+obj2.toPolar());//display object2 in polar form

System.out.println("Object1: "+obj1.display());//using display method

}

}