Make a program in Java Object Oriented language that performs Addition, Subtraction, Multiplication of two complex numbers (a+bi)
Make a program in Java Object Oriented language that performs Addition, Subtraction, Multiplication of two complex numbers (a+bi)
import java.util.Scanner;
public class Test{
//main method
public static void main(String[] args){
Scanner input=new Scanner(System.in);
System.out.print("Enter the first complex number: ");
double a=input.nextDouble();
double b=input.nextDouble();
Complex c1=new Complex(a,b);
System.out.print("Enter the second complex number: ");
double c=input.nextDouble();
double d=input.nextDouble();
Complex c2=new Complex(c,d);
System.out.println("("+c1+")"+" + "+"("+c2+")"+" = "+c1.add(c2));
System.out.println("("+c1+")"+" - "+"("+c2+")"+" = "+c1.subtract(c2));
System.out.println("("+c1+")"+" * "+"("+c2+")"+" = "+c1.multiply(c2));
System.out.println("("+c1+")"+" / "+"("+c2+")"+" = "+c1.divide(c2));
System.out.println("|"+c1+"| = "+c1.abs());
System.out.println();
try{
Complex c3=(Complex)c1.clone();
System.out.println(c1==c3);
System.out.println(c3.getRealPart());
System.out.println(c3.getImaginaryPart());
}catch(Exception e){e.printStackTrace();}
//end of main
}
}
//Complex.java
class Complex implements Cloneable
{
//data members
private double real,imaginary;
//constructors
public Complex(){
this.real=0;
this.imaginary=0;
}
public Complex(double real){
this.real=real;
this.imaginary=0;
}
public Complex(double real,double imaginary){
this.real=real;
this.imaginary=imaginary;
}
//member functions
public double getRealPart(){return this.real;}
public double getImaginaryPart(){return this.imaginary;}
@Override
public String toString(){
if(this.imaginary!=0){
return this.real+" + "+this.imaginary+"i";
}
return ""+this.real;
}
public String add(Complex obj){
return (this.real+obj.real)+" + "+(this.imaginary+obj.imaginary)+"i";
}
public String subtract(Complex obj){
return (this.real-obj.real)+" + "+(this.imaginary-obj.imaginary)+"i";
}
public String multiply(Complex obj){
return ((this.real*obj.real)-(this.imaginary*obj.imaginary))+" + "+((this.imaginary*obj.real)+(this.real*obj.imaginary))+"i";
}
public String divide(Complex obj){
return (this.real*obj.real+this.imaginary*obj.imaginary)/(Math.pow(obj.real,2)+Math.pow(obj.imaginary,2))+" + "+(this.imaginary*obj.real-this.real*obj.imaginary)/(Math.pow(obj.real,2)+Math.pow(obj.imaginary,2))+"i";
}
public double abs(){
return Math.sqrt(Math.pow(this.real,2)+Math.pow(this.imaginary,2));
}
@Override
protected Object clone() throws CloneNotSupportedException{
return super.clone();
}
//end of Complex
}
Step by step
Solved in 2 steps with 1 images