利用接口计算立体图形的表面积和体积
import java.util.Scanner;
interface 立体图形 {
double area();
double volume();
}
class Cone implements 立体图形{
int r;
int h;
public void SetCone(int r,int h) {
this.r = r;
this.h = h;
}
public double area(){
System.out.println("圆锥体的表面积:");
return Math.PI*r*(r+Math.sqrt(Math.pow(r,2)+Math.pow(h,2)));
}
public double volume(){
System.out.println("圆锥体的体积:");
return Math.PI*h*Math.pow(r,2)/3;
}
}
class Cylinder implements 立体图形{
int r;
int h;
public void SetCylinder(int r,int h) {
this.r = r;
this.h = h;
}
public double area(){
System.out.println("圆柱体的表面积:");
return 2*Math.PI*r*r+2*Math.PI*r*h;
}
public double volume(){
System.out.println("圆柱体的体积:");
return Math.PI*r*r*h;
}
}
public class Test5_2 {
public static void main(String[] args){
Scanner in=new Scanner(System.in);
Cylinder cylinder=new Cylinder();
System.out.println("请输入圆柱体的r和h:");
cylinder.SetCylinder(in.nextInt(),in.nextInt());
System.out.println(String.format("%.2f",cylinder.area()));
System.out.println(String.format("%.2f",cylinder.volume()));
Cone cone=new Cone();
System.out.println("请输入圆锥体的r和h:");
cone.SetCone(in.nextInt(),in.nextInt());
System.out.println(String.format("%.2f",cone.area()));
System.out.println(String.format("%.2f",cone.volume()));
}
}