You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

151 lines
3.8 KiB

package com.example.shape;
public abstract class Shape {
public abstract double getArea();
}
class Circle extends Shape {
private double radius;
private static final double PI = 3.1415926;
public Circle(double radius) {
if (radius <= 0) {
throw new IllegalArgumentException("半径必须大于0");
}
this.radius = radius;
}
@Override
public double getArea() {
return PI * radius * radius;
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
if (radius <= 0) {
throw new IllegalArgumentException("半径必须大于0");
}
this.radius = radius;
}
}
class Rectangle extends Shape {
private double length;
private double width;
public Rectangle(double length, double width) {
if (length <= 0 || width <= 0) {
throw new IllegalArgumentException("长和宽必须大于0");
}
this.length = length;
this.width = width;
}
@Override
public double getArea() {
return length * width;
}
public double getLength() {
return length;
}
public void setLength(double length) {
if (length <= 0) {
throw new IllegalArgumentException("长必须大于0");
}
this.length = length;
}
public double getWidth() {
return width;
}
public void setWidth(double width) {
if (width <= 0) {
throw new IllegalArgumentException("宽必须大于0");
}
this.width = width;
}
}
class Triangle extends Shape {
private double a;
private double b;
private double c;
public Triangle(double a, double b, double c) {
// 校验三边>0,且满足三角形三边关系(任意两边之和>第三边)
if (a <= 0 || b <= 0 || c <= 0) {
throw new IllegalArgumentException("边长必须大于0");
}
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 p = (a + b + c) / 2;
return Math.sqrt(p * (p - a) * (p - b) * (p - c));
}
public double getA() {
return a;
}
public void setA(double a) {
if (a <= 0) {
throw new IllegalArgumentException("边长必须大于0");
}
this.a = a;
if (a + b <= c || a + c <= b || b + c <= a) {
throw new IllegalArgumentException("不满足三角形三边关系,无法构成三角形");
}
}
public double getB() {
return b;
}
public void setB(double b) {
if (b <= 0) {
throw new IllegalArgumentException("边长必须大于0");
}
this.b = b;
if (a + b <= c || a + c <= b || b + c <= a) {
throw new IllegalArgumentException("不满足三角形三边关系,无法构成三角形");
}
}
public double getC() {
return c;
}
public void setC(double c) {
if (c <= 0) {
throw new IllegalArgumentException("边长必须大于0");
}
this.c = c;
if (a + b <= c || a + c <= b || b + c <= a) {
throw new IllegalArgumentException("不满足三角形三边关系,无法构成三角形");
}
}
}
class ShapeUtil {
public static void printArea(Shape shape) {
if (shape == null) {
System.out.println("图形对象不能为空!");
return;
}
double area = shape.getArea();
System.out.printf("该图形的面积为:%.2f%n", area);
}
}