Define a class called Complex with instance variables real, imag and instance methods
setData(), display(), add(). Write a Java program to add two complex numbers.
The prototype of add method is: public Complex add(Complex, Complex).
import java.util.Scanner;
class Complex {
private double real; // the real part
private double imag; // the imaginary part
/**
* Constructor
*/
public Complex() {}
/**
* Sets Data
* @param real
* @param imag
*/
public void setData(double real, double imag) {
this.real = real;
this.imag = imag;
}
/**
* Displays Complex number
*/
public void display() {
if(imag>0) {
System.out.println(String.format("%g + %gi", real, imag));
}else {
System.out.println(String.format("%g - %gi", real, Math.abs(imag)));
}
}
/**
* add two Complex numbers
* @param Complex1
* @param Complex2
* @return
*/
public Complex add(Complex Complex1, Complex Complex2) {
double sumReal = Complex1.getReal() + Complex2.getReal();
double sumImag = Complex1.getImag() + Complex2.getImag();
Complex complexSum=new Complex();
complexSum.setData(sumReal, sumImag);
return complexSum;
}
/**
* @return the real
*/
public double getReal() {
return real;
}
/**
* @param real the real to set
*/
public void setReal(double real) {
this.real = real;
}
/**
* @return the imag
*/
public double getImag() {
return imag;
}
/**
* @param imag the imag to set
*/
public void setImag(double imag) {
this.imag = imag;
}
}
public class Q200541 {
public static void main(String[] args) {
// Scanner object
Scanner in = new Scanner(System.in);
System.out.print("Enter the real part of Complex 1: ");
double real=in.nextDouble();
System.out.print("Enter the imaginary part of Complex 1: ");
double imag=in.nextDouble();
Complex Complex1=new Complex();
Complex1.setData(real, imag);
System.out.print("Enter the real part of Complex 2: ");
real=in.nextDouble();
System.out.print("Enter the imaginary part of Complex 2: ");
imag=in.nextDouble();
Complex Complex2=new Complex();
Complex2.setData(real, imag);
Complex sumComplex=Complex1.add(Complex1, Complex2);
System.out.println("Complex 1: ");
Complex1.display();
System.out.println("Complex 2: ");
Complex2.display();
System.out.println("Complex Sum: ");
sumComplex.display();
// close Scanner
in.close();
}
}
Comments
Leave a comment