2.修改Triangle类,重新定义为TriangleWithException类。 调用TriangleWithException类的构造方法,如果创建的三角形的违反了规则,抛出一个IllegalTriangleException异常。
时间: 2024-02-24 14:57:32 浏览: 62
下面是修改后的 TriangleWithException 类:
```
public class TriangleWithException {
private double sideA;
private double sideB;
private double sideC;
public TriangleWithException() {
sideA = 1;
sideB = 1;
sideC = 1;
}
public TriangleWithException(double s1, double s2, double s3) throws IllegalTriangleException {
if (isInvalid(s1, s2, s3)) {
throw new IllegalTriangleException(s1, s2, s3);
}
sideA = s1;
sideB = s2;
sideC = s3;
}
public double getA() {
return sideA;
}
public double getB() {
return sideB;
}
public double getC() {
return sideC;
}
public void setABC(double s1, double s2, double s3) throws IllegalTriangleException {
if (isInvalid(s1, s2, s3)) {
throw new IllegalTriangleException(s1, s2, s3);
}
sideA = s1;
sideB = s2;
sideC = s3;
}
public boolean isInvalid(double s1, double s2, double s3) {
return ((s1 + s2 <= s3) || (s1 + s3 <= s2) || (s2 + s3 <= s1) || s1 <= 0 || s2 <= 0 || s3 <= 0);
}
public double getArea() {
double s = (sideA + sideB + sideC) / 2;
return Math.pow(s * (s - sideA) * (s - sideB) * (s - sideC), 0.5);
}
public double getPerimeter() {
return sideA + sideB + sideC;
}
@Override
public String toString() {
return "The triangle: sideA = " + sideA + " , " + "sideB = " + sideB + " , " +
"sideC = " + sideC + "\n" +
"the area is " + getArea() + "\n" +
"the perimeter is " + getPerimeter();
}
}
```
在 TriangleWithException 类中,我们新增了一个叫做 IllegalTriangleException 的异常类,用于在创建三角形时抛出异常。在构造函数和 setABC 方法中,我们加入了对三角形是否合法的判断,如果不合法,则抛出 IllegalTriangleException 异常,否则正常赋值。
阅读全文