先创建一个Point类,然后定义Trianglele类。
在Trianglele类中定义三个Point的实体来表示一个三角形的三个点,再定义构造方法对这三个点进行初始化,然后定义两个方法求三角形的周长、面积。
定义一个测试类,在main()中创建一个对象,求给定三点的三角形的周长、面积。
package test1;
import java.util.*;
public class Main {
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
Point p1 = new Point(0, 0);
Point p2 = new Point(3, 0);
Point p3 = new Point(0, 4);
Trianglele t1 = new Trianglele(p1, p2, p3);
System.out.println("三角形的面积:" + t1.getArea());
System.out.println("三角形的周长:" + t1.getPerimeter());
sc.close();
}
}
class Point
{
double x, y;
public Point(double x, double y)
{
this.x = x;
this.y = y;
}
}
class Trianglele
{
private Point point1, point2, point3;
private double a, b, c;
public Trianglele(Point point1, Point point2, Point point3)
{
this.point1 = point1;
this.point2 = point2;
this.point3 = point3;
}
private void getSideLength()
{//求三边边长
a = Math.sqrt(Math.pow((point2.x - point1.x), 2) + Math.pow((point2.y - point1.y), 2));
b = Math.sqrt(Math.pow((point3.x - point2.x), 2) + Math.pow((point3.y - point2.y), 2));
c = Math.sqrt(Math.pow((point3.x - point1.x), 2) + Math.pow((point3.y - point1.y), 2));
}
public double getArea()
{
getSideLength();
double p = (a + b + c) / 2.0;
return Math.sqrt(p * (p-a)* (p-b) * (p-c));
}
public double getPerimeter()
{
return a + b + c;
}
}