Java 自设计一个线段类,其中包括平面坐标相关数据成员,和相关方法,并在主程序中判断三个线段是否组成三角形,如果不行输出各个线段的信息,如果可以输出三角形的面积和周长。
时间: 2024-05-09 21:20:30 浏览: 6
以下是 Java 中自设计的线段类:
```java
public class Line {
private double x1, y1, x2, y2; // 线段的两个端点坐标
public Line(double x1, double y1, double x2, double y2) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
}
public double length() { // 计算线段长度
double dx = x2 - x1;
double dy = y2 - y1;
return Math.sqrt(dx * dx + dy * dy);
}
public boolean isTriangle(Line b, Line c) { // 判断三个线段是否组成三角形
double ab = this.length();
double bc = b.length();
double ca = c.length();
return ab + bc > ca && ab + ca > bc && bc + ca > ab;
}
public double perimeter(Line b, Line c) { // 计算三角形周长
double ab = this.length();
double bc = b.length();
double ca = c.length();
return ab + bc + ca;
}
public double area(Line b, Line c) { // 计算三角形面积
double ab = this.length();
double bc = b.length();
double ca = c.length();
double p = (ab + bc + ca) / 2;
return Math.sqrt(p * (p - ab) * (p - bc) * (p - ca));
}
public String toString() { // 输出线段信息
return "(" + x1 + "," + y1 + ")-(" + x2 + "," + y2 + ")";
}
}
```
在主程序中,我们可以定义三个线段并对其进行判断:
```java
public static void main(String[] args) {
Line AB = new Line(0, 0, 3, 0);
Line BC = new Line(3, 0, 0, 4);
Line CA = new Line(0, 4, 0, 0);
if (AB.isTriangle(BC, CA)) {
double perimeter = AB.perimeter(BC, CA);
double area = AB.area(BC, CA);
System.out.println("三角形周长为:" + perimeter);
System.out.println("三角形面积为:" + area);
} else {
System.out.println("这三条线段不能组成三角形:");
System.out.println(AB);
System.out.println(BC);
System.out.println(CA);
}
}
```
输出结果为:
```
三角形周长为:12.0
三角形面积为:6.0
```