JAVA生成一个Shape数组,长度为20,其中奇数位置放圆,偶数位置放矩形
时间: 2024-03-20 07:42:24 浏览: 93
Shape.java
好的,以下是生成Shape数组的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 Main {
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 width = random.nextInt(10) + 1;
double height = random.nextInt(10) + 1;
shapes[i] = new Rectangle(width, height);
} else {
double radius = random.nextInt(5) + 1;
shapes[i] = new Circle(radius);
}
}
// do something with shapes array
}
}
```
这里我们定义了 Shape 抽象类作为基类,Circle 类和 Rectangle 类继承自 Shape 类,并且实现了各自的 area 方法计算面积。程序通过循环生成 20 个 Shape 对象,其中奇数位置放圆,偶数位置放矩形,每个圆和矩形的大小随机生成。最终得到的 shapes 数组就是所求的数组。
阅读全文