用java实现编写一个代表三角形的类。其中,三条边为三角形的属性,并封装有求三角形的面积和周长的方法。分别针对三条边为3,4,5和7,8,9的两个三角形进行测试。
时间: 2023-05-29 22:03:32 浏览: 147
Triangle.java
```java
public class Triangle {
private double a;
private double b;
private double c;
public Triangle(double a, double b, double c) {
this.a = a;
this.b = b;
this.c = c;
}
public double getA() {
return a;
}
public double getB() {
return b;
}
public double getC() {
return c;
}
public double getArea() {
double p = (a + b + c) / 2;
return Math.sqrt(p * (p - a) * (p - b) * (p - c));
}
public double getPerimeter() {
return a + b + c;
}
}
```
Test.java
```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("Sides: " + t1.getA() + ", " + t1.getB() + ", " + t1.getC());
System.out.println("Area: " + t1.getArea());
System.out.println("Perimeter: " + t1.getPerimeter());
Triangle t2 = new Triangle(7, 8, 9);
System.out.println("Triangle 2:");
System.out.println("Sides: " + t2.getA() + ", " + t2.getB() + ", " + t2.getC());
System.out.println("Area: " + t2.getArea());
System.out.println("Perimeter: " + t2.getPerimeter());
}
}
```
输出结果:
```
Triangle 1:
Sides: 3.0, 4.0, 5.0
Area: 6.0
Perimeter: 12.0
Triangle 2:
Sides: 7.0, 8.0, 9.0
Area: 26.832815729997478
Perimeter: 24.0
```
阅读全文