本题描述
1.定义抽象类Shape 属性:不可变静态常量 double PI
,值为 3.14
, 抽象方法:public double getPerimeter()
,public double getArea()
2.Rectangle与Circle类均继承自Shape类。 Rectangle类(属性:int width,length)、Circle类(属性:int radius)。 带参构造方法为 Rectangle(int width,int length)
,Circle(int radius)
。 toString
方法(Eclipse自动生成)
3.编写 double sumAllArea
方法计算并返回传入的形状数组中所有对象的面积和与 double sumAllPerimeter
方法计算并返回传入的形状数组中所有对象的周长和。
4.main方法 4.1 输入整型值n,然后建立n个不同的形状。如果输入rect,则依次输入宽、长。如果输入cir,则输入半径。 4.2 然后输出所有的形状的周长之和,面积之和。并将所有的形状信息以样例的格式输出。 提示:使用 Arrays.toString
。 4.3 最后输出每个形状的类型与父类型.使用类似 shape.getClass()
//获得类型, shape.getClass().getSuperclass()
//获得父类型;
注意:处理输入的时候使用混合使用 nextInt
与 nextLine
需注意行尾回车换行问题。
输入样例:复制
4
rect
3 1
rect
1 5
cir
1
cir
2
输出样例:复制
38.84
23.700000000000003
[Rectangle [width=3, length=1], Rectangle [width=1, length=5], Circle [radius=1], Circle [radius=2]]
class Rectangle,class Shape
class Rectangle,class Shape
class Circle,class Shape
class Circle,class Shape
import java.util.*;
public class Main {
public static double sumAllArea(double areaall)
{
return areaall;
}
public static double sumAllPerimeter(double perimeterall)
{
return perimeterall;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
sc.nextLine();
Shape []xz = new Shape[n];
double sumAllArea = 0, sumAllPerimeter = 0;
for(int i = 0;i < n;i++)
{
String ss = sc.nextLine();
if(ss.equals("rect"))
{
int a = sc.nextInt(),b = sc.nextInt();
sc.nextLine();
xz[i] = new Rectangle(a,b);
}
if(ss.equals("cir"))
{
int r = sc.nextInt();
sc.nextLine();
xz[i] = new Circle(r);
}
sumAllArea += xz[i].getArea();
sumAllPerimeter += xz[i].getPerimeter();
}
System.out.println(sumAllPerimeter(sumAllPerimeter));
System.out.println(sumAllArea(sumAllArea));
System.out.print("[");
for(int i = 0;i < n;i++)
{
if(i != 0)
System.out.print(", ");
System.out.print(xz[i].toString());
}
System.out.println("]");
for(int i = 0;i < n;i++)
{
System.out.println(xz[i].getClass()+","+xz[i].getClass().getSuperclass());
}
sc.close();
}
}
abstract class Shape {
final double PI = 3.14;
public abstract double getPerimeter();
public abstract double getArea();
}
class Rectangle extends Shape {
public int width;
public int length;
public Rectangle(int width, int length) {
super();
this.width = width;
this.length = length;
}
@Override
public String toString() {
return "Rectangle [width=" + width + ", length=" + length + "]";
}
public double getPerimeter() {
return 2*(width+length);
}
public double getArea() {
return width*length;
}
}
class Circle extends Shape {
public int radius;
public Circle(int radius) {
super();
this.radius = radius;
}
@Override
public String toString() {
return "Circle [radius=" + radius + "]";
}
public double getPerimeter() {
return 2*PI*radius;
}
public double getArea() {
return PI*radius*radius;
}
}