)编写一个 Triangle类代表三角形,在三角形中,任意两边之和总大于第三边。创建一个lllegalTriangleException异常类,在Triangle类的构造方法中,如果创建的三角形的边违反了这一规则,则抛出一个 legalTriangleException类对象。
时间: 2024-02-06 11:09:19 浏览: 72
下面是 Triangle 类和 IllegalTriangleException 异常类的示例代码:
```java
class Triangle {
private double side1, side2, 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 void setSide1(double side1) {
this.side1 = side1;
}
public double getSide2() {
return side2;
}
public void setSide2(double side2) {
this.side2 = side2;
}
public double getSide3() {
return side3;
}
public void setSide3(double side3) {
this.side3 = 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));
}
}
class IllegalTriangleException extends Exception {
public IllegalTriangleException(String message) {
super(message);
}
}
```
在 Triangle 类的构造方法中,我们使用 if 语句检查三角形的边是否符合规则。如果不符合规则,我们就抛出一个 IllegalTriangleException 异常。
下面是一个使用 Triangle 类的示例:
```java
public class Main {
public static void main(String[] args) {
try {
Triangle t1 = new Triangle(3, 4, 5);
System.out.println("Perimeter of t1: " + t1.getPerimeter());
System.out.println("Area of t1: " + t1.getArea());
Triangle t2 = new Triangle(1, 2, 3);
System.out.println("Perimeter of t2: " + t2.getPerimeter());
System.out.println("Area of t2: " + t2.getArea());
} catch (IllegalTriangleException ex) {
System.out.println(ex.getMessage());
}
}
}
```
在这个示例中,我们创建了两个 Triangle 对象。t1 的边符合规则,所以没有抛出异常。而 t2 的边不符合规则,所以我们捕获了 IllegalTriangleException 异常并打印出了异常消息。
阅读全文