先创建一个Point类,然后定义Triangle类。在Triangle类中定义三个Point的实体来表示一个三角形的三个顶点,再定义一个方法setPoints对这三个点进行初始化,然后定义两个方法perimeter和area求三角形的周长、面积。在main()中创建一个Triangle类的对象,求给定三个点的三角形的周长、面积。
package allTest; class Point { double x,y; public Point(double x,double y){ this.x = x; this.y = y; } } class Triangle { Point point1,point2,point3; private double a,b,c; public Triangle(Point point1,Point point2,Point point3){ this.point1 = point1; this.point2 = point2; this.point3 = point3; } public void Getlength(){ a = Math.sqrt(Math.pow((point1.x-point2.x),2)+Math.pow((point1.y-point2.y),2)); b = Math.sqrt(Math.pow((point2.x-point3.x),2)+Math.pow((point2.y-point3.y),2)); c = Math.sqrt(Math.pow((point3.x-point1.x),2)+Math.pow((point3.y-point1.y),2)); } public double GetArea(){ Getlength(); double m = (a+b+c)/2.0; return Math.sqrt(m*(m-a)*(m-b)*(m-c)); } public double Getall(){ Getlength(); return a+b+c; } } public class Test_5_2Main { 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 t1 = new Triangle(p1,p2,p3); System.out.println("周长:"+t1.Getall()); System.out.println("面积:"+t1.GetArea()); } }