Java编程实现圆柱体表面积和体积的计算,要求从键盘上输入底面圆的半径和圆柱体的高,然后输出结果。 (利用java的封装特性和创建对象完成题目)
时间: 2025-01-21 07:33:23 浏览: 40
好的,我可以为您提供一个使用Java编程实现圆柱体表面积和体积计算的示例。这个程序将利用Java的封装特性,并通过创建对象来完成题目要求。以下是代码实现:
```java
import java.util.Scanner;
class Cylinder {
// 私有属性
private double radius;
private double height;
// 构造方法
public Cylinder(double radius, double height) {
this.radius = radius;
this.height = height;
}
// Getter和Setter方法
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
// 计算表面积的方法
public double getSurfaceArea() {
return 2 * Math.PI * radius * (radius + height);
}
// 计算体积的方法
public double getVolume() {
return Math.PI * radius * radius * height;
}
}
public class CylinderCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 从键盘输入圆柱体的半径和高
System.out.print("请输入圆柱体的底面半径: ");
double radius = scanner.nextDouble();
System.out.print("请输入圆柱体的高: ");
double height = scanner.nextDouble();
// 创建Cylinder对象
Cylinder cylinder = new Cylinder(radius, height);
// 输出结果
System.out.printf("圆柱体的表面积是: %.2f\n", cylinder.getSurfaceArea());
System.out.printf("圆柱体的体积是: %.2f\n", cylinder.getVolume());
scanner.close();
}
}
```
这个程序的工作流程如下:
1. 定义了一个`Cylinder`类来表示圆柱体,包含私有属性`radius`和`height`。
2. 提供了构造方法、Getter和Setter方法。
3. 实现了`getSurfaceArea()`方法来计算表面积,公式为: 2 * π * r * (r + h)。
4. 实现了`getVolume()`方法来计算体积,公式为: π * r^2 * h。
5. 在`CylinderCalculator`类的`main`方法中:
- 使用`Scanner`从键盘读取用户输入的半径和高。
- 创建`Cylinder`对象。
- 调用对象的方法计算表面积和体积,并输出结果。
6. 使用`printf`方法格式化输出结果,保留两位小数。
这个程序充分利用了Java的封装特性,通过创建对象来完成任务,使得代码结构清晰,易于维护和扩展。
阅读全文
相关推荐


















