Description
有若干个直柱体(柱面与底面垂直),计算这些柱体的体积。已知柱体的底面有三种:圆、三角形和矩形。
Input
有多组数据。每组数据的第1项是底面类型,0——圆、1——三角形、2——矩形,其后分别是圆的半径,或三角形的三边长(三边一定能构成三角形),或矩形的长和宽,最后一项是柱体的高度。
Output
柱体的体积,保留两位小数。
Sample Input
2 20 10 15
0 10 20
1 3 4 5 20
Sample Output
3000.00
6283.19
120.00
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
Scanner in=new Scanner(System.in);
Shape shape;
double volume = 0,Area = 0;
double height,a,b,c,width,length,radius;
char input;
while(in.hasNext())
{
input=in.next().charAt(0);
if(input=='0')
{
radius=in.nextDouble();
height=in.nextDouble();
shape=new Circle(radius);
// Area=2*shape.area()+shape.perimeter()*height;
volume=shape.area()*height;
}
if(input=='2')
{
length=in.nextDouble();
width = in.nextDouble();
height = in.nextDouble();
shape=new Rectangle(width,length);
// Area=2*shape.area()+2*height*(width+length);
volume=shape.area()*height;
}
if(input=='1')
{
a=in.nextDouble();
b=in.nextDouble();
c=in.nextDouble();height=in.nextDouble();
shape=new Triangle(a,b,c);
// Area=2*shape.area()+shape.perimeter()*height;
volume=shape.area()*height;
}
System.out.printf("%.2f\n",volume);
}
}
}
abstract class Shape//抽象图形父类
{
public abstract double area();//抽象方法
public abstract double perimeter();
}
class Circle extends Shape//子类圆
{
private double radius;//半径
public Circle(double radius)//构造方法
{
this.radius=radius;
}
public double area()//重写父类的抽象方法计算面积
{
return Math.PI*radius*radius;
}
public double perimeter()//重写父类的抽象方法计算周长
{
return 2*Math.PI*radius;
}
}
class Rectangle extends Shape//子类矩形
{
private double width,height;//矩形宽和高
public Rectangle(double width,double height)//构造方法
{
this.width=width;
this.height=height;
}
public double area()//重写父类的抽象方法计算面积
{
return width*height;
}
public double perimeter()//重写父类的抽象方法计算周长
{
return 2*(width+height);
}
}
class Triangle extends Shape
{
private double a,b,c;
public Triangle(double a,double b,double c)
{
this.a=a;
this.b=b;
this.c=c;
}
public double area()
{
double p=(a+b+c)/2;
return Math.sqrt((p-a)*(p-b)*(p-c)*p);
}
public double perimeter()
{
return a+b+c;
}
}