Java定义圆形类,实例化三个圆形对象,输出各个圆形面积、周长及总个数。考虑到不能输入负数。
时间: 2024-09-26 21:02:39 浏览: 35
在Java中,我们可以创建一个`Circle`类,包含半径属性和计算面积和周长的方法。首先,确保定义圆的半径时进行有效性检查,避免输入负数。以下是相关的代码:
```java
public class Circle {
private double radius;
// 构造函数,接受半径并检查是否为正数
public Circle(double radius) {
if (radius < 0) {
throw new IllegalArgumentException("Radius cannot be negative.");
}
this.radius = radius;
}
// 计算面积的方法
public double getArea() {
return Math.PI * Math.pow(radius, 2);
}
// 计算周长的方法
public double getCircumference() {
return 2 * Math.PI * radius;
}
}
public class Main {
public static void main(String[] args) {
// 实例化三个圆形对象
Circle circle1 = new Circle(5);
Circle circle2 = new Circle(7);
Circle circle3 = new Circle(10);
// 输出每个圆形的面积和周长
System.out.println("Circle 1: Area = " + circle1.getArea() + ", Circumference = " + circle1.getCircumference());
System.out.println("Circle 2: Area = " + circle2.getArea() + ", Circumference = " + circle2.getCircumference());
System.out.println("Circle 3: Area = " + circle3.getArea() + ", Circumference = " + circle3.getCircumference());
// 总个数
int totalCircles = 3;
System.out.println("Total number of circles: " + totalCircles);
}
}
```
阅读全文