Java 为复数类的除法加上自定义异常处理。
时间: 2024-11-09 17:26:45 浏览: 35
java 自定义复数类
在Java中,我们可以创建一个名为`ComplexNumber`的复数类,用于表示复数,并添加一个`divide`方法来执行除法运算。为了处理可能出现的特殊情况,比如除数为零的情况,我们需要自定义一个异常——例如`DivideByZeroException`。下面是一个简单的示例:
```java
import java.util.Objects;
class ComplexNumber {
private double real;
private double imaginary;
public ComplexNumber(double real, double imaginary) {
this.real = real;
this.imaginary = imaginary;
}
// 获取和设置复数元素
public double getReal() { return real; }
public double getImaginary() { return imaginary; }
// 自定义除法方法,带异常处理
public ComplexNumber divide(ComplexNumber divisor) throws DivideByZeroException {
if (Objects.equals(divisor.getReal(), 0) && Objects.equals(divisor.getImaginary(), 0)) {
throw new DivideByZeroException("试图除以零");
}
double denominator = divisor.getReal() * divisor.getReal() + divisor.getImaginary() * divisor.getImaginary();
double quotientReal = (this.real * divisor.getReal() + this.imaginary * divisor.getImaginary()) / denominator;
double quotientImaginary = (this.imaginary * divisor.getReal() - this.real * divisor.getImaginary()) / denominator;
return new ComplexNumber(quotientReal, quotientImaginary);
}
}
class DivideByZeroException extends RuntimeException {
public DivideByZeroException(String message) {
super(message);
}
}
// 使用示例
public static void main(String[] args) {
try {
ComplexNumber c1 = new ComplexNumber(3, 4);
ComplexNumber c2 = new ComplexNumber(1, 1);
ComplexNumber result = c1.divide(c2);
System.out.println(result); // 打印结果
} catch (DivideByZeroException e) {
System.out.println(e.getMessage());
}
阅读全文