先创建一个Point类,然后定义Triangle类。在Triangle类中定义三个Point的实体来表示一个三角形的三个点,再定义一个方法setTri对这三个点进行初始化,然后定义两个方法求三角形的周长、面积。在main()中创建一个三角形对象,求给定三点的三角形的周长、面积。
时间: 2024-10-08 18:11:15 浏览: 60
首先,我们可以创建一个名为`Point`的类,它包含坐标信息:
```java
public class Point {
double x;
double y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
// getters and setters for x and y coordinates
}
```
接着,我们定义`Triangle`类,它内部持有三个`Point`类型的成员变量,并提供用于初始化的`setTri`方法以及计算周长和面积的方法:
```java
public class Triangle {
private Point point1;
private Point point2;
private Point point3;
public Triangle(Point p1, Point p2, Point p3) {
setTri(p1, p2, p3);
}
public void setTri(Point p1, Point p2, Point p3) {
this.point1 = p1;
this.point2 = p2;
this.point3 = p3;
}
public double getPerimeter() {
return Math.abs(point1.x - point2.x) + Math.abs(point2.x - point3.x) + Math.abs(point3.x - point1.x)
+ Math.abs(point1.y - point2.y) + Math.abs(point2.y - point3.y) + Math.abs(point3.y - point1.y);
}
public double getArea() {
double a = Math.abs((point1.x + point2.x + point3.x) / 2);
double b = Math.abs((point1.y + point2.y + point3.y) / 2);
return Math.sqrt(a * (a - point1.x) * (a - point2.x) * (a - point3.x)
+ b * (b - point1.y) * (b - point2.y) * (b - point3.y));
}
}
// In main method
public static void main(String[] args) {
Point p1 = new Point(0, 0);
Point p2 = new Point(5, 0);
Point p3 = new Point(0, 4); // Example points for a right triangle
Triangle triangle = new Triangle(p1, p2, p3);
System.out.println("Triangle perimeter: " + triangle.getPerimeter());
System.out.println("Triangle area: " + triangle.getArea());
阅读全文