定义一个Triangle类表示三角形,其中三个double型变量a、b、c表示三条边长。为该类定义两个构造方法:默认构造方法设置三角形的三条边长都为0.0; 带三个参数的构造方法通过传递三个参数创建三角形对象。定义求三角形面积的方法area), 面积计算公式为area=Math.sqrt(s*(s- -a)(s b)(-)),其中s-(a+b+e)/2。编写另一个程序测试这个三角形类的所有方法。
时间: 2024-02-09 13:13:28 浏览: 84
好的,这里是Triangle类的代码实现:
```java
public class Triangle {
private double a;
private double b;
private double c;
public Triangle() {
this.a = 0.0;
this.b = 0.0;
this.c = 0.0;
}
public Triangle(double a, double b, double c) {
this.a = a;
this.b = b;
this.c = c;
}
public double getA() {
return a;
}
public void setA(double a) {
this.a = a;
}
public double getB() {
return b;
}
public void setB(double b) {
this.b = b;
}
public double getC() {
return c;
}
public void setC(double c) {
this.c = c;
}
public double area() {
double s = (a + b + c) / 2.0;
double area = Math.sqrt(s * (s - a) * (s - b) * (s - c));
return area;
}
}
```
这里是测试程序的代码:
```java
public class TestTriangle {
public static void main(String[] args) {
Triangle t1 = new Triangle();
System.out.println("Triangle 1: a = " + t1.getA() + ", b = " + t1.getB() + ", c = " + t1.getC() + ", area = " + t1.area());
Triangle t2 = new Triangle(3.0, 4.0, 5.0);
System.out.println("Triangle 2: a = " + t2.getA() + ", b = " + t2.getB() + ", c = " + t2.getC() + ", area = " + t2.area());
t1.setA(6.0);
t1.setB(8.0);
t1.setC(10.0);
System.out.println("Triangle 1: a = " + t1.getA() + ", b = " + t1.getB() + ", c = " + t1.getC() + ", area = " + t1.area());
}
}
```
运行结果如下:
```
Triangle 1: a = 0.0, b = 0.0, c = 0.0, area = 0.0
Triangle 2: a = 3.0, b = 4.0, c = 5.0, area = 6.0
Triangle 1: a = 6.0, b = 8.0, c = 10.0, area = 24.0
```
其中,Triangle类有两个构造方法,一个默认的无参构造方法和一个带三个参数的构造方法。area方法计算三角形面积,测试程序中创建了两个Triangle对象t1和t2,并分别调用了它们的构造方法和area方法。最后,通过set方法修改了t1的三条边长,并再次调用area方法计算面积。
阅读全文