用java实现判断三角形的三条边能否构成三角形,并要求能判断出是等腰等边还是普通三角形,要求用到类的跨包使用
时间: 2024-10-10 18:16:17 浏览: 60
C语言程序设计练习题含程序及参考答案.pdf
在Java中,我们可以创建两个相关的类:`Triangle` 和 `SpecificTriangle` 来分别处理基本的三角形检查以及更具体的三角形类型判断。这里假设我们有两个包:`geometry` 和 `shapes`。
首先,在`geometry` 包下创建 `Triangle.java` 文件:
```java
// geometry/triangle/Triangle.java
package geometry.triangle;
public abstract class Triangle {
protected double a;
protected double b;
protected double c;
public Triangle(double sideA, double sideB, double sideC) {
if (sideA + sideB > sideC && sideA + sideC > sideB && sideB + sideC > sideA) {
this.a = sideA;
this.b = sideB;
this.c = sideC;
} else {
throw new IllegalArgumentException("Invalid sides for triangle");
}
}
// 具体的计算面积、周长的方法可以省略,因为这里是抽象类
public abstract String getType();
}
```
接着,在`shapes` 包下创建 `SpecificTriangle.java` 文件:
```java
// shapes/specific_triangle/SpecificTriangle.java
package shapes.specialtriangle;
import geometry.triangle.Triangle;
public class EquilateralTriangle extends Triangle {
public EquilateralTriangle(double side) {
super(side, side, side);
}
@Override
public String getType() {
return "Equilateral";
}
}
public class IsoscelesTriangle extends Triangle {
private boolean isSymmetric;
public IsoscelesTriangle(double base, double equalSide, double otherSide) {
super(base, equalSide, otherSide);
if (base == equalSide || equalSide == otherSide) {
isSymmetric = true;
}
}
@Override
public String getType() {
if (isSymmetric) {
return "Isosceles";
} else {
return "Isosceles (not symmetric)";
}
}
}
public class ScaleneTriangle extends Triangle {
public ScaleneTriangle(double sideA, double sideB, double sideC) {
super(sideA, sideB, sideC);
}
@Override
public String getType() {
return "Scalene";
}
}
```
现在可以在需要的地方使用这些类来判断三角形类型:
```java
// 使用示例
public static void main(String[] args) {
Triangle equi = new EquilateralTriangle(5);
System.out.println(equi.getType()); // 输出 "Equilateral"
Triangle iso = new IsoscelesTriangle(4, 4, 6);
System.out.println(iso.getType()); // 输出 "Isosceles (not symmetric)"
Triangle scalene = new ScaleneTriangle(3, 4, 5);
System.out.println(scalene.getType()); // 输出 "Scalene"
}
```
阅读全文