)先创建一个Point类,然后定义Trianglele 类。在Trianglele类中定义三个Point的实体来表示一个三角形的三个点,再定义其构造方法对这三个点进行初始化,然后定义两个方法求三角形的周长、面积。在测试主类中创建一个对象,求给定三点的三角形的周长、面积。
时间: 2024-09-21 14:06:14 浏览: 76
先创建一个Point类,然后定义Trianglele类
4星 · 用户满意度95%
在Java中,我们可以按照以下步骤创建一个`Point`类和`Triangle`类来实现这个功能:
首先,我们定义一个`Point`类,它将包含坐标信息:
```java
public class Point {
private double x;
private double y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
// getters and setters for x and y coordinates
public double getX() { return x; }
public void setX(double x) { this.x = x; }
public double getY() { return y; }
public void setY(double y) { this.y = y; }
@Override
public String toString() {
return "Point{" +
"x=" + x +
", y=" + y +
'}';
}
```
接着,我们创建一个`Triangle`类,其中包含三个`Point`对象并提供计算周长和面积的方法:
```java
public class Triangle {
private Point pointA;
private Point pointB;
private Point pointC;
public Triangle(Point pointA, Point pointB, Point pointC) {
this.pointA = pointA;
this.pointB = pointB;
this.pointC = pointC;
}
// Calculate perimeter
public double getPerimeter() {
return Math.abs(pointA.getX() - pointB.getX()) + Math.abs(pointB.getX() - pointC.getX()) + Math.abs(pointC.getX() - pointA.getX())
+ Math.abs(pointA.getY() - pointB.getY()) + Math.abs(pointB.getY() - pointC.getY()) + Math.abs(pointC.getY() - pointA.getY());
}
// Calculate area using Heron's formula (assuming non-degenerate triangle)
public double getArea() {
double a = Math.abs(pointA.getX() - pointB.getX());
double b = Math.abs(pointB.getX() - pointC.getX());
double c = Math.abs(pointC.getX() - pointA.getX());
double s = (a + b + c) / 2.0;
return Math.sqrt(s * (s - a) * (s - b) * (s - c));
}
// Override toString() method for better representation
@Override
public String toString() {
return "Triangle{" +
"pointA=" + pointA +
", pointB=" + pointB +
", pointC=" + pointC +
", perimeter=" + getPerimeter() +
", area=" + getArea() +
'}';
}
}
```
最后,在测试主类`Main`中,我们可以实例化一个`Triangle`对象,并计算给定三点的三角形周长和面积:
```java
public class Main {
public static void main(String[] args) {
Point p1 = new Point(0, 0);
Point p2 = new Point(3, 4);
Point p3 = new Point(6, 0);
Triangle triangle = new Triangle(p1, p2, p3);
System.out.println("Triangle: " + triangle);
System.out.println("Perimeter: " + triangle.getPerimeter());
System.out.println("Area: " + triangle.getArea());
}
}
```
当你运行`main`方法时,会输出三角形的信息以及它的周长和面积。
阅读全文