Description
先定义一个接口IComVolume,有一个方法computeVolume,有一个常量PI为3.14。
然后定义一个实现该接口的圆柱体Cylinder类,有double类型的半径和高两个属性。
再定义一个实现该接口的长方体Block类,有double类型的长和宽、高三个属性。
要求main方法中至少包含如下代码(这些语句不要求必须放在一起):
IComVolume icv;
icv=new Cylinder(r,h);
icv=new Block(a,b,c);
icv.computeVolume();
Input
第一行输入数据的组数N,然后有N组数据。每组数据由一个字符和几个浮点数组成,第一个是图形类型,c表示Cylinder,b表示Block;如果前面是c,后面跟两个浮点,分别为圆柱底半径和高;如果是b后面跟三个浮点,分别为长宽高。
Output
图形类型及其体积(精度保留2位)。
Sample Input
4
c 10 10
b 20 10 10
b 5 4 5
c 20 5
Sample Output
Cylinder:3140.00
Block:2000.00
Block:100.00
Cylinder:6280.00
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
int t;
double r,h ,a,b,c;
t=in.nextInt();
IComVolume icv;
for(int i=0;i<t;i++)
{
char m;
m=in.next().charAt(0);
if(m=='c')
{
r=in.nextDouble();
h=in.nextDouble();
icv=new Cylinder(r,h);
r=icv.computeVolume();
System.out.printf("Cylinder:%.2f\n",r);
}
if(m=='b')
{
a=in.nextDouble();
b=in.nextDouble();
c=in.nextDouble();
icv=new Block(a,b,c);
a=icv.computeVolume();
System.out.printf("Block:%.2f\n",a);
}
}
}}
abstract class IComVolume//抽象图形父类
{
public abstract double computeVolume();//抽象方法
public static final float PI=(float) 3.14;
}
class Cylinder extends IComVolume{
private double radius;
private double high;
public Cylinder(double radius,double high)//构造方法
{
this.radius=radius;
this.high=high;
}
@Override
public double computeVolume() {
// TODO Auto-generated method stub
return PI*radius*radius*high;
}
}
class Block extends IComVolume{
private double a;
private double b;
private double c;
public Block(double a,double b,double c)
{
this.a=a;
this.b=b;
this.c=c;
}
@Override
public double computeVolume() {
// TODO Auto-generated method stub
return a*b*c;
}
}
该博客主要介绍用Java编写的图形体积计算程序。先定义接口IComVolume,再实现圆柱体Cylinder类和长方体Block类。程序从输入获取图形类型及尺寸数据,计算并输出各图形的体积,输入包含多组数据,输出结果保留两位小数。
850

被折叠的 条评论
为什么被折叠?



