使用java语言,本题要求编写复数类,该类至少包括加法、减法、乘法、除法的方法。还要编写ComplexDivException类,该类继承自Exception类,且至少包含两个数据成员,一个为错误代码,一个为错误信息。当复数类除数为0时,需要抛出该异常。编写测试类,测试以上两个类。
时间: 2024-02-16 12:59:59 浏览: 23
好的,这是一个Java编程的问题,我会尽力回答。下面是我的解答:
```java
// 复数类
public class Complex {
private double real;
private double imaginary;
public Complex(double real, double imaginary) {
this.real = real;
this.imaginary = imaginary;
}
public Complex add(Complex other) {
double real = this.real + other.real;
double imaginary = this.imaginary + other.imaginary;
return new Complex(real, imaginary);
}
public Complex subtract(Complex other) {
double real = this.real - other.real;
double imaginary = this.imaginary - other.imaginary;
return new Complex(real, imaginary);
}
public Complex multiply(Complex other) {
double real = this.real * other.real - this.imaginary * other.imaginary;
double imaginary = this.imaginary * other.real + this.real * other.imaginary;
return new Complex(real, imaginary);
}
public Complex divide(Complex other) throws ComplexDivException {
double denominator = other.real * other.real + other.imaginary * other.imaginary;
if (denominator == 0) {
throw new ComplexDivException(1, "Divisor can not be zero.");
}
double real = (this.real * other.real + this.imaginary * other.imaginary) / denominator;
double imaginary = (this.imaginary * other.real - this.real * other.imaginary) / denominator;
return new Complex(real, imaginary);
}
@Override
public String toString() {
return real + " + " + imaginary + "i";
}
}
// 复数除法异常类
public class ComplexDivException extends Exception {
private int errorCode;
private String errorMessage;
public ComplexDivException(int errorCode, String errorMessage) {
this.errorCode = errorCode;
this.errorMessage = errorMessage;
}
public int getErrorCode() {
return errorCode;
}
public String getErrorMessage() {
return errorMessage;
}
}
// 测试类
public class ComplexTest {
public static void main(String[] args) {
Complex a = new Complex(3, 4);
Complex b = new Complex(1, 2);
try {
Complex c = a.divide(b);
System.out.println(a + " / " + b + " = " + c);
} catch (ComplexDivException e) {
System.out.println("Error: " + e.getErrorCode() + ", " + e.getErrorMessage());
}
}
}
```
这个程序中,我们定义了一个复数类 `Complex`,包含复数的实部和虚部,以及加法、减法、乘法和除法的方法。在除法方法中,当除数为0时,会抛出 `ComplexDivException` 异常。我们还定义了一个测试类 `ComplexTest`,用于测试 `Complex` 和 `ComplexDivException` 类。在测试类中,我们创建了两个复数,然后进行除法运算,并处理可能出现的异常。
希望这个解答能够帮到你!