Bilei 3 weeks ago
parent
commit
5d8da98051
  1. BIN
      w5/PlantUML.png
  2. 81
      w5/ShapeAreaCalculator.java
  3. BIN
      w5/实验报告.docx

BIN
w5/PlantUML.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 161 KiB

81
w5/ShapeAreaCalculator.java

@ -0,0 +1,81 @@
abstract class Shape {
public abstract double getArea();
}
class Circle extends Shape {
private double radius;
public Circle(double radius) {
if (radius <= 0) {
throw new IllegalArgumentException("半径必须为正数");
}
this.radius = radius;
}
@Override
public double getArea() {
return Math.PI * radius * radius;
}
}
class Rectangle extends Shape {
private double width;
private double height;
public Rectangle(double width, double height) {
if (width <= 0 || height <= 0) {
throw new IllegalArgumentException("宽和高必须为正数");
}
this.width = width;
this.height = height;
}
@Override
public double getArea() {
return width * height;
}
}
class Triangle extends Shape {
private double a;
private double b;
private double c;
public Triangle(double a, double b, double c) {
if (a <= 0 || b <= 0 || c <= 0) {
throw new IllegalArgumentException("边长必须为正数");
}
if (a + b <= c || a + c <= b || b + c <= a) {
throw new IllegalArgumentException("三边不满足三角形构成条件");
}
this.a = a;
this.b = b;
this.c = c;
}
@Override
public double getArea() {
double s = (a + b + c) / 2;
return Math.sqrt(s * (s - a) * (s - b) * (s - c));
}
}
class ShapeUtil {
public static void printArea(Shape shape) {
if (shape == null) {
System.out.println("图形对象不能为空");
return;
}
System.out.printf("图形面积:%.2f%n", shape.getArea());
}
}
public class ShapeAreaCalculator {
public static void main(String[] args) {
try {
Shape circle = new Circle(3);
System.out.print("圆形:");
ShapeUtil.printArea(circle);
Shape rectangle = new Rectangle(4, 5);
System.out.print("矩形:");
ShapeUtil.printArea(rectangle);
Shape triangle = new Triangle(3, 4, 5);
System.out.print("三角形:");
ShapeUtil.printArea(triangle);
} catch (IllegalArgumentException e) {
System.out.println("错误:" + e.getMessage());
}
}
}

BIN
w5/实验报告.docx

Binary file not shown.
Loading…
Cancel
Save