用java自设计一个线段类,其中包括平面坐标相关数据成员,和相关方法,并在主程序中判断三个线段是否组成三角形,如果不行输出各个线段的信息,如果可以输出三角形的面积和周长。
时间: 2024-05-19 20:14:30 浏览: 78
//线段类
public class Line {
private double x1;
private double y1;
private double x2;
private double 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 getLength() {
return Math.sqrt(Math.pow((x2 - x1), 2) + Math.pow((y2 - y1), 2));
}
//判断三个线段是否能组成三角形
public static boolean isTriangle(Line l1, Line l2, Line l3) {
double a = l1.getLength();
double b = l2.getLength();
double c = l3.getLength();
if (a + b > c && a + c > b && b + c > a) {
return true;
} else {
return false;
}
}
//计算三角形面积
public static double getTriangleArea(Line l1, Line l2, Line l3) {
double a = l1.getLength();
double b = l2.getLength();
double c = l3.getLength();
double p = (a + b + c) / 2;
return Math.sqrt(p * (p - a) * (p - b) * (p - c));
}
//计算三角形周长
public static double getTrianglePerimeter(Line l1, Line l2, Line l3) {
double a = l1.getLength();
double b = l2.getLength();
double c = l3.getLength();
return a + b + c;
}
//输出线段信息
public void printInfo() {
System.out.println("(" + x1 + ", " + y1 + ") -> (" + x2 + ", " + y2 + ")");
System.out.println("Length: " + getLength());
}
}
//主程序
public class Main {
public static void main(String[] args) {
Line l1 = new Line(0, 0, 3, 0);
Line l2 = new Line(0, 0, 0, 4);
Line l3 = new Line(3, 0, 0, 4);
if (Line.isTriangle(l1, l2, l3)) {
System.out.println("Triangle Area: " + Line.getTriangleArea(l1, l2, l3));
System.out.println("Triangle Perimeter: " + Line.getTrianglePerimeter(l1, l2, l3));
} else {
System.out.println("Can't form a triangle!");
System.out.println("Line 1:");
l1.printInfo();
System.out.println("Line 2:");
l2.printInfo();
System.out.println("Line 3:");
l3.printInfo();
}
}
}
阅读全文