用java根据传递的参数计算圆球、圆柱、圆锥、长方体、正方体,的体积
时间: 2023-12-28 14:19:48 浏览: 27
以下是一个Java程序,根据传递的参数计算圆球、圆柱、圆锥、长方体、正方体的体积:
```java
public class VolumeCalculator {
public static void main(String[] args) {
if (args.length < 2) {
System.out.println("Please provide a shape and its dimensions.");
return;
}
String shape = args[0];
switch (shape) {
case "sphere":
if (args.length < 2) {
System.out.println("Please provide the radius of the sphere.");
return;
}
double sphereRadius = Double.parseDouble(args[1]);
double sphereVolume = 4.0 / 3.0 * Math.PI * Math.pow(sphereRadius, 3);
System.out.printf("The volume of the sphere is %.2f cubic units.%n", sphereVolume);
break;
case "cylinder":
if (args.length < 3) {
System.out.println("Please provide the radius and height of the cylinder.");
return;
}
double cylinderRadius = Double.parseDouble(args[1]);
double cylinderHeight = Double.parseDouble(args[2]);
double cylinderVolume = Math.PI * Math.pow(cylinderRadius, 2) * cylinderHeight;
System.out.printf("The volume of the cylinder is %.2f cubic units.%n", cylinderVolume);
break;
case "cone":
if (args.length < 3) {
System.out.println("Please provide the radius and height of the cone.");
return;
}
double coneRadius = Double.parseDouble(args[1]);
double coneHeight = Double.parseDouble(args[2]);
double coneVolume = 1.0 / 3.0 * Math.PI * Math.pow(coneRadius, 2) * coneHeight;
System.out.printf("The volume of the cone is %.2f cubic units.%n", coneVolume);
break;
case "rectangular prism":
if (args.length < 4) {
System.out.println("Please provide the length, width, and height of the rectangular prism.");
return;
}
double prismLength = Double.parseDouble(args[1]);
double prismWidth = Double.parseDouble(args[2]);
double prismHeight = Double.parseDouble(args[3]);
double prismVolume = prismLength * prismWidth * prismHeight;
System.out.printf("The volume of the rectangular prism is %.2f cubic units.%n", prismVolume);
break;
case "cube":
if (args.length < 2) {
System.out.println("Please provide the length of the cube.");
return;
}
double cubeLength = Double.parseDouble(args[1]);
double cubeVolume = Math.pow(cubeLength, 3);
System.out.printf("The volume of the cube is %.2f cubic units.%n", cubeVolume);
break;
default:
System.out.println("Invalid shape.");
break;
}
}
}
```
该程序接受命令行参数,第一个参数为形状名称,后续参数为形状的维度。程序使用switch语句根据形状名称计算体积,并使用printf方法来打印结果。在每个情况下,程序检查是否提供了足够的参数,并在必要时提示用户提供缺少的参数。