编写一个代表一角形的类(Triangle.java)。其中,三条边a,b.c(数据类型为double类型)为二角形的属性,该类封装有求一角形的面积和周长的方法。分别针对给定的三条边进行测试(给定三条边已经满足三角形构成条件),输出面积和周长保留2位小数。
时间: 2024-10-08 12:23:24 浏览: 66
```java
public class Triangle {
private double a;
private double b;
private double c;
// 构造方法,检查输入是否满足三角形条件
public Triangle(double sideA, double sideB, double sideC) {
if (sideA + sideB > sideC && sideA + sideC > sideB && sideB + sideC > sideA) {
this.a = sideA;
this.b = sideB;
this.c = sideC;
} else {
throw new IllegalArgumentException("Invalid sides for a triangle.");
}
}
// Getter methods
public double getSideA() {
return a;
}
public double getSideB() {
return b;
}
public double getSideC() {
return c;
}
// Setter methods
public void setSideA(double sideA) {
this.a = sideA;
}
public void setSideB(double sideB) {
this.b = sideB;
}
public void setSideC(double sideC) {
this.c = sideC;
}
// Calculate perimeter
public double calculatePerimeter() {
return a + b + c;
}
// Calculate area using Heron's formula
public double calculateArea() {
double semiPerimeter = calculatePerimeter() / 2;
return Math.sqrt(semiPerimeter * (semiPerimeter - a) * (semiPerimeter - b) * (semiPerimeter - c));
}
// Test method
public void test(double sideA, double sideB, double sideC) {
try {
Triangle triangle = new Triangle(sideA, sideB, sideC);
System.out.printf("Triangle with sides %.2f, %.2f, %.2f:\n", sideA, sideB, sideC);
System.out.printf("Perimeter: %.2f\n", triangle.calculatePerimeter());
System.out.printf("Area: %.2f\n", triangle.calculateArea());
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
}
// Test example
public static void main(String[] args) {
double sideA = 3.0;
double sideB = 4.0;
double sideC = 5.0; // Pythagorean triple
Triangle triangle = new Triangle(sideA, sideB, sideC);
triangle.test(sideA, sideB, sideC);
}
```
这个`Triangle`类包含三条边作为属性,并在构造函数中检查它们是否能组成有效的三角形。提供求周长和面积的方法,最后的`test`方法用于测试给定的三边长度。如果输入的边长不符合三角形条件,会抛出异常并在`main`方法中捕获并显示错误消息。
阅读全文