7-2 jmu-Java-03面向对象基础-03-形状 (20 分)
##1. 定义长方形类与圆形类Circle
长方形类-类名:Rectangle
,private属性:int width,length
圆形类-类名:Circle
,private属性:int radius
编写构造函数:
带参构造函数:Rectangle(width, length)
,Circle(radius)
编写方法:
public int getPerimeter()
,求周长。
public int getArea()
,求面积。
toString
方法,使用Eclipse自动生成。
注意:
1、计算圆形的面积与周长,使用Math.PI。
2、求周长和面积时,应先计算出其值(带小数位),然后强制转换为int再返回。
##2. main方法
1、输入2行长与宽,创建两个Rectangle对象放入相应的数组。
2、输入2行半径,创建两个Circle对象放入相应的数组。
3、输出1:上面2个数组中的所有对象的周长加总。
4、输出2:上面2个数组中的所有对象的面积加总。
5、最后需使用Arrays.deepToString
分别输出上面建立的Rectangle数组与Circle数组
思考:如果初次做该题会发现代码冗余严重。使用继承、多态思想可以大幅简化上述代码。
输入样例:
1 2
3 4
7
1
输出样例:
69
170
[Rectangle [width=1, length=2], Rectangle [width=3, length=4]]
[Circle [radius=7], Circle [radius=1]]
代码
import java.util.Scanner;
import java.util.Arrays;
class Rectangle {
private int width;
private int length;
public Rectangle(int width, int length) {
super();
this.width = width;
this.length = length;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
@Override
public String toString() {
return "Rectangle [width=" + width + ", length=" + length + "]";
}
public int getPerimeter() {
return (int) (this.length + this.width) * 2;
}
public int getArea() {
return (int) this.length * this.width;
}
}
class Circle {
private int radius;
public Circle(int radius) {
super();
this.radius = radius;
}
public int getRadius() {
return radius;
}
public void setRadius(int radius) {
this.radius = radius;
}
@Override
public String toString() {
return "Circle [radius=" + radius + "]";
}
public int getPerimeter() {
return (int) (2 * Math.PI * this.radius);
}
public int getArea() {
return (int) (Math.PI * this.radius * this.radius);
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Rectangle[] rec = new Rectangle[2];
Circle[] cir = new Circle[2];
int m = scanner.nextInt();
int n = scanner.nextInt();
rec[0] = new Rectangle(m, n);
int mm = scanner.nextInt();
int nn = scanner.nextInt();
rec[1] = new Rectangle(mm, nn);
int r = scanner.nextInt();
cir[0] = new Circle(r);
int rr = scanner.nextInt();
cir[1] = new Circle(rr);
System.out
.println(rec[0].getPerimeter() + rec[1].getPerimeter() + cir[0].getPerimeter() + cir[1].getPerimeter());
System.out.println(rec[0].getArea() + rec[1].getArea() + cir[0].getArea() + cir[1].getArea());
System.out.println(Arrays.deepToString(rec));
System.out.println(Arrays.deepToString(cir));
}
}