Complex Number Program in Java

/**
 * Program to create a class for Complex Number.
 * The class should contain real and imginary properties along
 * add, subtract and product on complex numbers.
 *
 * Test your class on two complex numbers
 */

class Complex {
private float real;
private float img;

/**
* Default constructor
*/
Complex() {
this.real = this.img = .0f;
}

/**
* Parameterized conctructor 1
*/
Complex(float val) {
this.real = this.img = val;
}

/**
* Parameterized conctructor 2
*/
Complex(float real, float img) {
this.real = real;
this.img = img;
}

/**
* Addition
*/
public Complex add(Complex c) {
return new Complex(this.real + c.real, this.img + c.img);
}

/**
* Subtraction
*/
public Complex subtract(Complex c) {
return new Complex(this.real - c.real, this.img - c.img);
}

/**
* Multiplication
* a + bi X c + di = (ac - bd) + (ad + cb)i
*/
public Complex product(Complex c) {
return new Complex(this.real*c.real - this.img*c.img, this.real*c.img + this.img*c.real);
}

  /**
   * Overriding toString
   */
@Override
public String toString() {
return this.real + ((this.img < .0f) ? " - " : " + ") + Math.abs(this.img) + "i";
}
}

public class ComplexNumberTest {
public static void main(String[] args) {
Complex c1 = new Complex(1.25f, 2.15f);
Complex c2 = new Complex(2.15f, -1.25f);

Complex c3 = c1.add(c2);
System.out.println(c3);

c3 = c1.subtract(c2);
System.out.println(c3);

c3 = c1.product(c2);
System.out.println(c3);
}
}

Comments

Popular posts from this blog

Zeller's Congruence

Property Event-Delegation

Method with variable arguments