I have here a code that should print the sum and difference of two complex numbers. The instructions given are:
make the methods add
, subtract
, and
public void print(){
if(this.imag <0){
System.out.println(this.real+" "+this.imag+"i");
}
if(this.imag >0){
System.out.println(this.real+"+"+this.imag+"i");
}
}
Perhaps this is not what you're looking for, but to make the number be printed isn't enough to make something like this in your print method?
System.out.print("The number is: " +real +"+i" +imag);
You incorrectly use print merhod. if you want to see correct result you need to rewrite add method like this:
public void add(Complex num, Complex num2){
this.real = num.real + num2.real;
this.imag = num.imag + num2.imag;
}
rewrite subtract method also.
public void subtract(Complex num){
this.real = real - num.real;
this.imag = imag - num.imag;
}
Now main method look like this:
public static void main(String[] args) {
Complex c1 = new Complex(4.0, 8.5);
Complex c2 = new Complex(8.0, 4.5);
Complex result = new Complex(8.0, 4.5);
result.add(c1,c2);
result.print();
result.subtract(c1,c2);
result.print();
print method as I told previously look like:
public void print(){
System.out.println(real + " " + imag +"i");
}
Explanation:
In your code you have error. You add c2 to c1 and then subtract c2 frim c1 and then print result. Mathematically this looks like : c1= c1+c2-c2;