Compare commits
4 Commits
d34fc4f882
...
91d628f9c5
| Author | SHA1 | Date |
|---|---|---|
|
|
91d628f9c5 | 3 weeks ago |
|
|
5d8da98051 | 3 weeks ago |
|
|
8e41793cd7 | 1 month ago |
|
|
aef2673b0f | 2 months ago |
5 changed files with 84 additions and 0 deletions
@ -0,0 +1,2 @@ |
|||||
|
# java |
||||
|
|
||||
@ -0,0 +1 @@ |
|||||
|
HelloWorld |
||||
|
After Width: | Height: | Size: 161 KiB |
@ -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()); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
Binary file not shown.
Loading…
Reference in new issue