用Java编写定义一个三角形类Triangle,要求提供3条边长信息,以及求周长、求面积等行为。然后再定义一个测试类TriangleTest,作为主程序来测试Triangle类。一些要求如下: (1)边长数据类型为普通整型即可,不能为负数。 (2)提供一个boolean型的私有成员canTri,用于判断三条边长能否构成三角形,并用公开方法isTri返回该私有成员变量canTri的状态。 (3)提供求周长的方法。 (4)提供求面积的方法。使用海伦公式:
时间: 2024-03-02 22:54:32 浏览: 94
好的,以下是Java代码实现:
Triangle类:
```java
public class Triangle {
private int sideA;
private int sideB;
private int sideC;
private boolean canTri;
public Triangle(int a, int b, int c) {
sideA = a;
sideB = b;
sideC = c;
canTri = isTriangle();
}
private boolean isTriangle() {
return sideA + sideB > sideC && sideB + sideC > sideA && sideA + sideC > sideB;
}
public boolean isTri() {
return canTri;
}
public int getPerimeter() {
if (!canTri) {
return -1;
}
return sideA + sideB + sideC;
}
public double getArea() {
if (!canTri) {
return -1;
}
double p = (sideA + sideB + sideC) / 2.0;
return Math.sqrt(p * (p - sideA) * (p - sideB) * (p - sideC));
}
}
```
TriangleTest类:
```java
public class TriangleTest {
public static void main(String[] args) {
Triangle t1 = new Triangle(3, 4, 5);
System.out.println("Can form triangle: " + t1.isTri());
System.out.println("Perimeter: " + t1.getPerimeter());
System.out.println("Area: " + t1.getArea());
Triangle t2 = new Triangle(3, 4, 8);
System.out.println("Can form triangle: " + t2.isTri());
System.out.println("Perimeter: " + t2.getPerimeter());
System.out.println("Area: " + t2.getArea());
}
}
```
测试结果:
```
Can form triangle: true
Perimeter: 12
Area: 6.0
Can form triangle: false
Perimeter: -1
Area: -1.0
```
阅读全文