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

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

ID: 3690157 • Letter: W

Question

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 polar in polar (r, theta) format.

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

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.

Explanation / Answer

package complex;

public class Complex {
  
   private double real;
   private double imaginary;
  
  
   public Complex(double real, double imaginary) {
       super();
       this.real = real;
       this.imaginary = imaginary;
   }
   public double getReal() {
       return real;
   }
   public void setReal(double real) {
       this.real = real;
   }
   public double getImaginary() {
       return imaginary;
   }
   public void setImaginary(double imaginary) {
       this.imaginary = imaginary;
   }
  
   public void displayInCartesianFormat() {
       char operand;
       operand = this.imaginary > 0 ? '+' : '-';
       System.out.println(this.real + " " + operand + " j" + this.imaginary);
   }
  
   public void displayInPolarFormat() {
       double mag = Math.sqrt(this.real*this.real + this.imaginary*this.imaginary);
       double slope = Math.toDegrees(Math.atan2(this.imaginary, this.real));
       System.out.println(mag + ", " + slope);
   }
  
   public void plus(Complex obj) {
       this.real+= obj.getReal();
       this.imaginary+= obj.getImaginary();
   }
  
   public static void main(String[] args) {
       Complex object1 = new Complex(3, 4);
       Complex object2 = new Complex(4, -5);
      
       object2.plus(object1);
      
       object1.displayInCartesianFormat();
       object2.displayInPolarFormat();
   }

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote