Use the Point class in the Java class library to design a triangle class (Triangle), and output the area of the triangle.
时间: 2023-06-02 07:06:05 浏览: 54
好的,您可以通过以下代码实现:
```
import java.awt.Point;
public class Triangle {
private Point p1, p2, p3;
public Triangle(Point p1, Point p2, Point p3) {
this.p1 = p1;
this.p2 = p2;
this.p3 = p3;
}
public double getArea() {
double a = p1.distance(p2);
double b = p1.distance(p3);
double c = p2.distance(p3);
double s = (a + b + c) / 2;
return Math.sqrt(s * (s - a) * (s - b) * (s - c));
}
}
// 在其他地方可以通过以下方式使用Triangle类
Triangle triangle = new Triangle(new Point(0, 0), new Point(0, 5), new Point(5, 0));
double area = triangle.getArea();
System.out.println("Triangle area is " + area);
```
这里我们使用了Point类来表示三角形的三个定点,利用海伦公式计算三角形面积。