声明复数类Complex,成员变量包括实部和虚部,类型均为double。要求该类具有 (1)实现多个构造方法(如无参构造方法、1个参数构造方法,2个参数构造方法,字符串参数的构造方法)。 (2)使用getter和setter完成属性的访问和修改 (3)成员方法包括实现复数加法add、减法minus、乘法multiply,计算模长length (4)重写equals()方法,只有当两个复数实部和虚部都相等时,才返回真 (5)重写toString(),输出复数信息 (6)在main方法中,使用实际数据测试成员方法
时间: 2024-02-12 07:08:24 浏览: 20
好的,以下是Complex类的实现代码:
```java
public class Complex {
private double real;
private double imag;
// 无参构造方法
public Complex() {
this.real = 0.0;
this.imag = 0.0;
}
// 1个参数构造方法
public Complex(double real) {
this.real = real;
this.imag = 0.0;
}
// 2个参数构造方法
public Complex(double real, double imag) {
this.real = real;
this.imag = imag;
}
// 字符串参数的构造方法
public Complex(String str) {
String[] parts = str.split("\\+");
this.real = Double.parseDouble(parts[0]);
this.imag = Double.parseDouble(parts[1].substring(0, parts[1].length() - 1));
}
// getter和setter
public double getReal() {
return real;
}
public void setReal(double real) {
this.real = real;
}
public double getImag() {
return imag;
}
public void setImag(double imag) {
this.imag = imag;
}
// 复数加法
public Complex add(Complex other) {
double newReal = this.real + other.real;
double newImag = this.imag + other.imag;
return new Complex(newReal, newImag);
}
// 复数减法
public Complex minus(Complex other) {
double newReal = this.real - other.real;
double newImag = this.imag - other.imag;
return new Complex(newReal, newImag);
}
// 复数乘法
public Complex multiply(Complex other) {
double newReal = this.real * other.real - this.imag * other.imag;
double newImag = this.real * other.imag + this.imag * other.real;
return new Complex(newReal, newImag);
}
// 计算模长
public double length() {
return Math.sqrt(real * real + imag * imag);
}
// 重写equals()方法
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Complex)) return false;
Complex complex = (Complex) o;
return Double.compare(complex.real, real) == 0 && Double.compare(complex.imag, imag) == 0;
}
// 重写toString()方法
@Override
public String toString() {
if (imag < 0)
return String.format("%.2f-%.2fi", real, Math.abs(imag));
else
return String.format("%.2f+%.2fi", real, imag);
}
}
```
下面是在main方法中使用实际数据测试成员方法的代码:
```java
public static void main(String[] args) {
Complex c1 = new Complex(1.0, 2.0);
Complex c2 = new Complex("3.0-4.0i");
System.out.println("c1: " + c1);
System.out.println("c2: " + c2);
Complex c3 = c1.add(c2);
System.out.println("c1 + c2 = " + c3);
Complex c4 = c1.minus(c2);
System.out.println("c1 - c2 = " + c4);
Complex c5 = c1.multiply(c2);
System.out.println("c1 * c2 = " + c5);
System.out.println("|c1| = " + c1.length());
System.out.println("|c2| = " + c2.length());
System.out.println("c1 equals c2? " + c1.equals(c2));
}
```
输出结果如下:
```
c1: 1.00+2.00i
c2: 3.00-4.00i
c1 + c2 = 4.00-2.00i
c1 - c2 = -2.00+6.00i
c1 * c2 = 11.00-2.00i
|c1| = 2.23606797749979
|c2| = 5.0
c1 equals c2? false
```