有若干个直柱体(底面与柱面垂直),其底面可能是圆形、矩形或三角形。
已知柱体的高度、圆的半径、矩形的宽度和高度及三角形的三边长(一定能构成三角形),计算柱体的体积和表面 (包括两个底的面积)
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=='C')
{
height=in.nextDouble();
radius=in.nextDouble();
shape=new Circle(radius);
Area=2*shape.area()+shape.perimeter()*height;
volume=shape.area()*height;
}
if(input=='R')
{
height=in.nextDouble();
length=in.nextDouble();
width=in.nextDouble();
shape=new Rectangle(width,length);
Area=2*shape.area()+shape.perimeter()*height;
volume=shape.area()*height;
}
if(input=='T')
{
height=in.nextDouble();
a=in.nextDouble();
b=in.nextDouble();
c=in.nextDouble();
shape=new Triangle(a,b,c);
Area=2*shape.area()+shape.perimeter()*height;
volume=shape.area()*height;
}
System.out.println(Area+" "+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));
}
public double perimeter() {
return a+b+c;
}
}