用Java编写以下内容:用Java设定三维立体图形ThreeDimen:圆球、圆柱、圆锥、长方体、正方体,根据传递的参数计算三维图形的体积。
时间: 2023-06-02 22:05:37 浏览: 119
好的,以下是用Java编写的代码:
public class ThreeDimen {
public static double getVolume(String shape, double... params) {
switch(shape.toLowerCase()) {
case "sphere":
return (4.0/3.0) * Math.PI * Math.pow(params[0], 3);
case "cylinder":
return Math.PI * Math.pow(params[0], 2) * params[1];
case "cone":
return (1.0/3.0) * Math.PI * Math.pow(params[0], 2) * params[1];
case "cuboid":
return params[0] * params[1] * params[2];
case "cube":
return Math.pow(params[0], 3);
default:
throw new IllegalArgumentException("Invalid shape name");
}
}
}
使用示例:
double sphereVolume = ThreeDimen.getVolume("sphere", 5.0);
double cylinderVolume = ThreeDimen.getVolume("cylinder", 2.0, 5.0);
double coneVolume = ThreeDimen.getVolume("cone", 3.0, 4.0);
double cuboidVolume = ThreeDimen.getVolume("cuboid", 2.0, 3.0, 4.0);
double cubeVolume = ThreeDimen.getVolume("cube", 5.0);
阅读全文