用JAVA编写一个代表三角形的类其中三条边为三角形的属性并封装有求三角形的面积和周长的方法分别针对三条边为345和789的两个三角形进行测试
时间: 2023-05-29 13:04:11 浏览: 170
Triangle.java
```
public class Triangle {
private double side1;
private double side2;
private double side3;
public Triangle(double s1, double s2, double s3) {
side1 = s1;
side2 = s2;
side3 = s3;
}
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 p = getPerimeter() / 2;
return Math.sqrt(p * (p - side1) * (p - side2) * (p - side3));
}
}
```
Test.java
```
public class Test {
public static void main(String[] args) {
Triangle t1 = new Triangle(3, 4, 5);
System.out.println("Triangle 1:");
System.out.println("Perimeter: " + t1.getPerimeter());
System.out.println("Area: " + t1.getArea());
Triangle t2 = new Triangle(7, 8, 9);
System.out.println("Triangle 2:");
System.out.println("Perimeter: " + t2.getPerimeter());
System.out.println("Area: " + t2.getArea());
}
}
```
输出结果:
```
Triangle 1:
Perimeter: 12.0
Area: 6.0
Triangle 2:
Perimeter: 24.0
Area: 26.832815729997478
```
阅读全文