利用java语言实现 编写一个代表三角形的类。其中,三条边为三角形的属性,并封装有求三角形的面积和周长的方法。分别针对三条边为3,4,5和7,8,9的两个三角形进行测试。
时间: 2023-05-29 18:07:00 浏览: 57
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 getPerimeter() {
return side1 + side2 + side3;
}
public double getArea() {
double p = (side1 + side2 + side3) / 2;
return Math.sqrt(p * (p - side1) * (p - side2) * (p - side3));
}
}
```
Main.java:
```
public class Main {
public static void main(String[] args) {
Triangle triangle1 = new Triangle(3, 4, 5);
System.out.println("Triangle1 perimeter: " + triangle1.getPerimeter());
System.out.println("Triangle1 area: " + triangle1.getArea());
Triangle triangle2 = new Triangle(7, 8, 9);
System.out.println("Triangle2 perimeter: " + triangle2.getPerimeter());
System.out.println("Triangle2 area: " + triangle2.getArea());
}
}
```
Output:
```
Triangle1 perimeter: 12.0
Triangle1 area: 6.0
Triangle2 perimeter: 24.0
Triangle2 area: 26.832815729997478
```
阅读全文