定义一个具有三条边的三角形类Triangle。在三角形中,任意两边之和大于第三边。三角形类Triangle写遵从这一个规则。定义一个IllegalTriangleException类,修改类Triangle的构造方法,如果创建的三角形的边违反了这一规则,则抛出一个IllegalTriangleException对象。 程序框架如下所示: public class Main { public static void main(String [ ] args) { Scanner in=new Scanner(System.in); double side1,side2,side3; side1=in.nextDouble(); side2=in.nextDouble(); side3=in.nextDouble(); //下面的代码创建Triangle对象,使用try catch处理异常 .... } class Triangle { private double side1; private double side2; private double side3; public Triangle(double side1,double side2,double side3) throws IllegalTriangleException {//初始化,如果出现两条边之和小于等于第三边,则抛出 IllegalTriangleException异常对象 .... } } class IllegalTriangleException extends Exception {//下面的代码定义异常类 ... }
时间: 2024-01-26 20:04:33 浏览: 95
好的,以下是符合要求的 Triangle 类的代码实现:
```
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
double side1, side2, side3;
side1 = in.nextDouble();
side2 = in.nextDouble();
side3 = in.nextDouble();
try {
Triangle triangle = new Triangle(side1, side2, side3);
System.out.println("Triangle created successfully!");
} catch (IllegalTriangleException e) {
System.out.println("Failed to create triangle: " + e.getMessage());
}
}
}
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 || side2 + side3 <= side1 || side1 + side3 <= side2) {
throw new IllegalTriangleException("The sum of any two sides must be greater than the third side.");
}
this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
}
}
class IllegalTriangleException extends Exception {
public IllegalTriangleException(String message) {
super(message);
}
}
```
在上面的代码中,我们定义了 Triangle 类和 IllegalTriangleException 类。在 Triangle 类的构造函数中,我们检查了三角形的三条边是否符合要求,如果不符合,则抛出 IllegalTriangleException 异常。在 Main 类的 main 函数中,我们使用 try-catch 块来处理 Triangle 类的构造函数可能抛出的异常。
阅读全文