package exercises; /** * * @author Lefteris Moussiades */ public class Complex { private double r; private double f; public static boolean stdNot; public Complex(double r, double f) { this.r=r; this.f=f; } public void setR(double r) { this.r=r; } public void setF(double f) { this.f=f; } public double getR() { return r; } public double getF() { return f; } @Override public String toString() { if (stdNot) return "("+r+", "+f+")"; else return r+"+"+f+"i"; } public void assign(Complex c) { r=c.r; f=c.f; } public Complex add(Complex c) { double real; double fant; real=r+c.r; fant=f+c.f; return new Complex(real, fant); } public Complex subtract(Complex c) { double real; double fant; real=r-c.r; fant=f-c.f; return new Complex(real, fant); } public Complex multiply(Complex c) { double real=r*c.r-f*c.f; double fant=r*c.f+f*c.r; return new Complex(real, fant); } public Complex divide(Complex c) { double x2=Math.pow(c.r, 2); double c2=Math.pow(c.f, 2); double real=c.r/(x2+c2); double fant=-c.f/(x2+c2); Complex oneByZ=new Complex(real,fant); return this.multiply(oneByZ); } // @Override // public boolean equals(Object o) { // Complex c=(Complex)o; // return r==c.r && f==c.f; // } @Override public int hashCode() { int hash = 3; hash = 67 * hash + (int) (Double.doubleToLongBits(this.r) ^ (Double.doubleToLongBits(this.r) >>> 32)); hash = 67 * hash + (int) (Double.doubleToLongBits(this.f) ^ (Double.doubleToLongBits(this.f) >>> 32)); return hash; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Complex other = (Complex) obj; if (Double.doubleToLongBits(this.r) != Double.doubleToLongBits(other.r)) { return false; } if (Double.doubleToLongBits(this.f) != Double.doubleToLongBits(other.f)) { return false; } return true; } public static void main(String[] args) { Complex c1=new Complex(2,3); Complex c2=new Complex(5,7); c1.assign(c2); c2.setF(9); System.out.println(c1+" "+c2); Complex sum=c1.add(c2); Complex sub=sum.subtract(c2); System.out.println("c1+c2 = " + c1 +" + "+c2+" = "+c1.add(c2)); System.out.println("sum-c2 = " + sum +" - "+c2+" = "+sum.subtract(c2)); } }