定义一个具有三条边的三角形类Triangle。在三角形中,任意两边之和大于第三边。三角形类Triangle写遵从这一个规则。定义一个IllegalTriangleException类,修改类Triangle的构造方法,如果创建的三角形的边违反了这一规则,则抛出一个IllegalTriangleException对象。
时间: 2023-05-14 22:04:54 浏览: 244
Triangle类的代码如下:
```
public class Triangle {
private double side1;
private double side2;
private double side3;
public Triangle(double side1, double side2, double side3) throws IllegalTriangleException {
if (side1 + side2 <= side3 || side1 + side3 <= side2 || side2 + side3 <= side1) {
throw new IllegalTriangleException("Invalid triangle sides");
}
this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
}
public double getSide1() {
return side1;
}
public double getSide2() {
return side2;
}
public double getSide3() {
return side3;
}
public double getPerimeter() {
return side1 + side2 + side3;
}
public double getArea() {
double s = getPerimeter() / 2;
return Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));
}
}
```
IllegalTriangleException类的代码如下:
```
public class IllegalTriangleException extends Exception {
public IllegalTriangleException(String message) {
super(message);
}
}
```
阅读全文