创建复数类Complex,并实现复数的基本运算。

具体要求:

  • 复数类有两个私有属性,实部a,虚部b;
  • 编写复数类的无参构造方法和包含所有属性的构造方法;
  • 编写所有属性的Getters和Setters方法;
  • 重写toString()方法,实现自定义复数的输出信息,如复数5+4i输出(5+4i);
  • 编写复数运算类ComplexCal,包含复数的加、减运算。
  • public static Complex add(Complex c1,Complex c2)
  • public static Complex sub(Complex c1,Complex c2)

(6)编写Main测试类,在main()方法中进行复数类的测试。

  package test.sy2;
class Complex {
    private double a;
    private double b;

    //无参构造方法
    public Complex() {}

    //包含所有属性的构造方法
    public Complex(double a, double b) {
        this.a = a;
        this.b = b;
    }

    //Getters和Setters方法
    public double getA() {
        return a;
    }

    public void setA(double a) {
        this.a = a;
    }

    public double getB() {
        return b;
    }

    public void setB(double b) {
        this.b = b;
    }
    //重写toString()方法,实现自定义复数的输出信息
    @Override
    public String toString() {
        return "(" + a + "+" + b + "i)";
    }
}


public class ComplexCal {
    //复数的加运算
    public static Complex add(Complex c1, Complex c2) {
        return new Complex(c1.getA() + c2.getA(), c1.getB() + c2.getB());
    }

    //复数的减运算
    public static Complex sub(Complex c1, Complex c2) {
        return new Complex(c1.getA() - c2.getA(), c1.getB() - c2.getB());
    }
}

class Main1 {
    public static void main(String[] args) {
        Complex complex1 = new Complex(3, 4);
        Complex complex2 = new Complex(5, 6);

        System.out.println("Complex 1: " + complex1);
        System.out.println("Complex 2: " + complex2);
        //ComplexCal a=new ComplexCal();
        //System.out.println(a.add(complex1,complex2));
        System.out.println("复数加法: "+ ComplexCal.add(complex1, complex2));
        System.out.println("复数减法: " + ComplexCal.sub(complex1, complex2));
    }
}