创建圆形类,创建实例变量半径,创建类变量PI,并为PI赋初始值3.14 创建求周⻓的⽅法,求⾯积的⽅法。要求将计算的结构返回给调⽤⽅法。 创建2个圆形,半径分别为10和20,分别调⽤求周⻓和求⾯积的⽅法,计算出两个圆形的周 ⻓和⾯积。 最后⽤System.out对象分别打印周⻓和⾯积。
时间: 2024-03-26 09:38:18 浏览: 11
好的,我来为您解答。
首先,我们需要创建一个圆形类。以下是代码:
```java
public class Circle {
private double radius; // 实例变量,半径
private static double PI = 3.14; // 类变量,π
// 构造方法
public Circle(double radius) {
this.radius = radius;
}
// 求周长的方法
public double getPerimeter() {
return 2 * PI * radius;
}
// 求面积的方法
public double getArea() {
return PI * radius * radius;
}
}
```
接着,我们创建两个圆形实例,分别为半径为10和20。代码如下:
```java
Circle circle1 = new Circle(10);
Circle circle2 = new Circle(20);
```
然后,我们调用圆形类中的求周长和求面积的方法,计算出两个圆形的周长和面积,并将结果保存在变量中。代码如下:
```java
double perimeter1 = circle1.getPerimeter();
double perimeter2 = circle2.getPerimeter();
double area1 = circle1.getArea();
double area2 = circle2.getArea();
```
最后,我们使用System.out对象分别打印周长和面积。代码如下:
```java
System.out.println("第一个圆的周长为:" + perimeter1);
System.out.println("第二个圆的周长为:" + perimeter2);
System.out.println("第一个圆的面积为:" + area1);
System.out.println("第二个圆的面积为:" + area2);
```
完整代码如下:
```java
public class Circle {
private double radius; // 实例变量,半径
private static double PI = 3.14; // 类变量,π
// 构造方法
public Circle(double radius) {
this.radius = radius;
}
// 求周长的方法
public double getPerimeter() {
return 2 * PI * radius;
}
// 求面积的方法
public double getArea() {
return PI * radius * radius;
}
}
public class Main {
public static void main(String[] args) {
Circle circle1 = new Circle(10);
Circle circle2 = new Circle(20);
double perimeter1 = circle1.getPerimeter();
double perimeter2 = circle2.getPerimeter();
double area1 = circle1.getArea();
double area2 = circle2.getArea();
System.out.println("第一个圆的周长为:" + perimeter1);
System.out.println("第二个圆的周长为:" + perimeter2);
System.out.println("第一个圆的面积为:" + area1);
System.out.println("第二个圆的面积为:" + area2);
}
}
```
输出结果:
```
第一个圆的周长为:62.800000000000004
第二个圆的周长为:125.60000000000001
第一个圆的面积为:314.0
第二个圆的面积为:1256.0
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)