用JAVA编写一个代表三角形的类,其中3条边为三角形的属性,并封装有求三角形的面积和周长的方法。分别利用3条边为3、4、5、和7、8、9的两个三角形进行测试
时间: 2023-05-30 21:02:45 浏览: 67
计算三角形的面积和周长(java)
5星 · 资源好评率100%
```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;
return Math.sqrt(p * (p - side1) * (p - side2) * (p - side3));
}
public double getPerimeter() {
return side1 + side2 + side3;
}
public static void main(String[] args) {
Triangle triangle1 = new Triangle(3, 4, 5);
System.out.println("Triangle 1: Side 1 = " + triangle1.getSide1() +
", Side 2 = " + triangle1.getSide2() +
", Side 3 = " + triangle1.getSide3() +
", Area = " + triangle1.getArea() +
", Perimeter = " + triangle1.getPerimeter());
Triangle triangle2 = new Triangle(7, 8, 9);
System.out.println("Triangle 2: Side 1 = " + triangle2.getSide1() +
", Side 2 = " + triangle2.getSide2() +
", Side 3 = " + triangle2.getSide3() +
", Area = " + triangle2.getArea() +
", Perimeter = " + triangle2.getPerimeter());
}
}
```
输出:
```
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
```
阅读全文