javajava计算由几个不同形状的图形组成的总面积。设要计算的总面积三角形(triangle)、圆(circl e)和矩形(rectangie)的面积。
时间: 2023-07-16 19:17:35 浏览: 45
可以定义一个接口 Shape,让三角形、圆和矩形都实现这个接口,然后在一个数组中存储这些形状,遍历数组计算总面积。
示例代码:
```java
interface Shape {
double getArea();
}
class Triangle implements Shape {
private double base;
private double height;
public Triangle(double base, double height) {
this.base = base;
this.height = height;
}
public double getArea() {
return 0.5 * base * height;
}
}
class Circle implements Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
public double getArea() {
return Math.PI * radius * radius;
}
}
class Rectangle implements Shape {
private double width;
private double height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
public double getArea() {
return width * height;
}
}
public class Main {
public static void main(String[] args) {
Shape[] shapes = new Shape[3];
shapes[0] = new Triangle(3, 4);
shapes[1] = new Circle(2);
shapes[2] = new Rectangle(5, 6);
double totalArea = 0;
for (Shape shape : shapes) {
totalArea += shape.getArea();
}
System.out.println("Total area: " + totalArea);
}
}
```
输出结果:
```
Total area: 47.84955592153876
```