JAVA,编写一个test类,生成一个Shape数组,长度为20,其中奇数位置放圆(半径一次加3),偶数位置放矩形(长为50,宽一次加2)
时间: 2024-03-20 20:42:28 浏览: 63
好的,以下是实现要求的Java代码:
```java
import java.util.Random;
abstract class Shape {
abstract double area();
}
class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
public double area() {
return Math.PI * radius * radius;
}
}
class Rectangle extends Shape {
private double width;
private double height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
public double area() {
return width * height;
}
}
public class Test {
public static void main(String[] args) {
Shape[] shapes = new Shape[20];
Random random = new Random();
for (int i = 0; i < 20; i++) {
if (i % 2 == 0) {
double radius = random.nextInt(5) + 1;
shapes[i] = new Circle(radius * 3);
} else {
double width = 50;
double height = random.nextInt(10) + 1;
shapes[i] = new Rectangle(width, height * 2);
}
}
// do something with shapes array
}
}
```
这里我们定义了 Shape 抽象类作为基类,Circle 类和 Rectangle 类继承自 Shape 类,并且实现了各自的 area 方法计算面积。程序通过循环生成 20 个 Shape 对象,其中奇数位置放圆,半径每次加 3,偶数位置放矩形,长为 50,宽每次加 2,高是随机生成的数乘以 2。最终得到的 shapes 数组就是所求的数组。
阅读全文