先创建一个Point类,然后定义Triangle类。在Triangle类中定义3个Point的对象用来表示一个三角形的三个点,再定义一个方法setTri对这三个点进行初始化,然后定义两个方法求三角形的周长、面积。在main()中创建一个三角形对象,求给定三点的三角形的周长、面积。将setTri改用构造方法实现初始化用java编译
时间: 2023-06-03 07:04:13 浏览: 66
好的,我明白了。以下是Java代码实现:
Point类:
```
public class Point {
private double x;
private double y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
public double distance(Point other) {
double dx = x - other.getX();
double dy = y - other.getY();
return Math.sqrt(dx * dx + dy * dy);
}
}
```
Triangle类:
```
public class Triangle {
private Point p1;
private Point p2;
private Point p3;
public Triangle(Point p1, Point p2, Point p3) {
this.p1 = p1;
this.p2 = p2;
this.p3 = p3;
}
public double getPerimeter() {
double side1 = p1.distance(p2);
double side2 = p2.distance(p3);
double side3 = p3.distance(p1);
return side1 + side2 + side3;
}
public double getArea() {
double side1 = p1.distance(p2);
double side2 = p2.distance(p3);
double side3 = p3.distance(p1);
double s = (side1 + side2 + side3) / 2;
return Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));
}
public void setTri(Point p1, Point p2, Point p3) {
this.p1 = p1;
this.p2 = p2;
this.p3 = p3;
}
}
```
在main()方法中创建对象并计算周长和面积:
```
public static void main(String[] args) {
Point p1 = new Point(0, 0);
Point p2 = new Point(3, 0);
Point p3 = new Point(0, 4);
Triangle t = new Triangle(p1, p2, p3);
System.out.println("周长是:" + t.getPerimeter());
System.out.println("面积是:" + t.getArea());
}
```
输出结果:
```
周长是:12.0
面积是:6.0
```
阅读全文