(1)编写一个Circle类代表圆,提供默认构造方法和创建指定半径的构造方法。创建一个InvalidRadiusException异常类,当半径为负数时,setRadius()方法抛出一个InvalidRadiusException 类对象。
时间: 2024-05-05 21:20:52 浏览: 44
CircleTest_java_设计一个circle_点类_圆类_
5星 · 资源好评率100%
下面是实现Circle类的代码:
```java
public class Circle {
private double radius;
public Circle() {
this.radius = 0;
}
public Circle(double radius) throws InvalidRadiusException {
if (radius < 0) {
throw new InvalidRadiusException("半径不能为负数!");
}
this.radius = radius;
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) throws InvalidRadiusException {
if (radius < 0) {
throw new InvalidRadiusException("半径不能为负数!");
}
this.radius = radius;
}
public double getArea() {
return Math.PI * radius * radius;
}
}
```
其中,InvalidRadiusException类的代码如下:
```java
public class InvalidRadiusException extends Exception {
public InvalidRadiusException(String message) {
super(message);
}
}
```
使用示例:
```java
public static void main(String[] args) {
try {
Circle c1 = new Circle();
System.out.println("半径为:" + c1.getRadius() + ",面积为:" + c1.getArea());
Circle c2 = new Circle(-1);
System.out.println("半径为:" + c2.getRadius() + ",面积为:" + c2.getArea());
} catch (InvalidRadiusException e) {
System.out.println(e.getMessage());
}
}
```
输出:
```
半径为:0.0,面积为:0.0
半径不能为负数!
```
阅读全文