Description
先定义一个抽象Graphic类,有求面积的computeArea抽象方法(返回值为面积,圆周率取3.14);
然后定义一个从Graphic派生的Circle类,有double类型的半径,以及重写的computeArea抽象方法。
再定义一个从Graphic派生的Rectangle类,有double类型的长和宽属性,以及重写的computeArea抽象方法。
要求main方法中至少包含如下代码(这些语句不要求必须放在一起):
Graphic g;
g=new Circle®;
g=new Rectangle(a,b);
g.computeArea();
Input
第一行输入数据的组数N,然后有N组数据。每组数据由一个字符和几个浮点数组成,第一个如何是’c’表示Circle,是’r’表示Rectangle;如果前面是’c’,后面跟一个浮点,如果是’r’后面跟两个浮点。
Output
图形类型及其面积(精度保留2位)。
Sample Input
4
c 10
r 20 10
r 5 4
c 20
Sample Output
Circle:314.00
Rectangle:200.00
Rectangle:20.00
Circle:1256.00
import java.util.*;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
int n;
Scanner in=new Scanner (System.in);
n=in.nextInt();
Graphic g ;
int i=0;
do
{i++;
char f;
f=in.next().charAt(0);
if(f=='r')
{float a=in.nextFloat();
float b=in.nextFloat();
g=new Rectangle(a,b);
g.computeArea();
}
if(f=='c')
{
float r=in.nextFloat();
g=new Circle(r);
g.computeArea();
}
}
while(i<n);
}
}
abstract class Graphic
{
public abstract void computeArea();
}
class Circle extends Graphic
{
private double radius;
public Circle(double radius)
{
this.radius=radius;
}
public void computeArea()
{
System.out.printf("Circle:%.2f\n",radius*radius*3.14);
}
}
class Rectangle extends Graphic
{
double length;
private double width;
public Rectangle(double length,double width)
{
this.length=length;
this.width=width;
}
public void computeArea()
{
System.out.printf("Rectangle:%.2f\n",length*width);
}
}