用java编写一个代表三角形的类,其中3条边为三角形的属性,并封装有求三角形的面积和周长的方法。分别利用3条边为3、4、5和7、8、9的两个三角形进行测试。
时间: 2023-05-28 22:03:49 浏览: 74
Triangle.java
```
public class Triangle {
private double side1;
private double side2;
private double side3;
public Triangle(double side1, double side2, double side3) {
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 getArea() {
double p = (side1 + side2 + side3) / 2.0;
return Math.sqrt(p * (p - side1) * (p - side2) * (p - side3));
}
public double getPerimeter() {
return side1 + side2 + side3;
}
}
```
TestTriangle.java
```
public class TestTriangle {
public static void main(String[] args) {
Triangle triangle1 = new Triangle(3, 4, 5);
System.out.println("Triangle 1:");
System.out.println("Side 1: " + triangle1.getSide1());
System.out.println("Side 2: " + triangle1.getSide2());
System.out.println("Side 3: " + triangle1.getSide3());
System.out.println("Area: " + triangle1.getArea());
System.out.println("Perimeter: " + triangle1.getPerimeter());
System.out.println();
Triangle triangle2 = new Triangle(7, 8, 9);
System.out.println("Triangle 2:");
System.out.println("Side 1: " + triangle2.getSide1());
System.out.println("Side 2: " + triangle2.getSide2());
System.out.println("Side 3: " + triangle2.getSide3());
System.out.println("Area: " + triangle2.getArea());
System.out.println("Perimeter: " + triangle2.getPerimeter());
}
}
```
Output:
```
Triangle 1:
Side 1: 3.0
Side 2: 4.0
Side 3: 5.0
Area: 6.0
Perimeter: 12.0
Triangle 2:
Side 1: 7.0
Side 2: 8.0
Side 3: 9.0
Area: 26.832815729997478
Perimeter: 24.0
```
阅读全文