爪哇国新游记之二----用于计算三角形面积的Point类和TAngle类

这次尝试用两个类完成一个面积计算任务:

Point类代表平面上的点:

public class Point {
    private float x;
    private float y;

    public Point(float x,float y){
        this.x=x;
        this.y=y;
    }

    public float getX() {
        return x;
    }

    public void setX(float x) {
        this.x = x;
    }

    public float getY() {
        return y;
    }

    public void setY(float y) {
        this.y = y;
    }
}

TAngle这个类表示三个点控制的三角形

import com.ibm.Point;

public class TAngle {
    private Point p1;
    private Point p2;
    private Point p3;

    public TAngle(Point p1,Point p2,Point p3){
        this.p1=p1;
        this.p2=p2;
        this.p3=p3;
    }

    private double getLength(Point op1,Point op2){
        float x=op1.getX()-op2.getX();
        float y=op1.getY()-op2.getY();
        double l=(double)x*x+y*y;

        return Math.sqrt(l);
    }

    private double getP(){
        return (getLength(p1,p2)+getLength(p2,p3)+getLength(p3,p1))/2;
    }

    public double getArea(){
        double p=getP();
        double area=Math.sqrt(p*(p-getLength(p1,p2))*(p-getLength(p2,p3))*(p-getLength(p3,p1)));

        return area;
    }

    public static void main(String[] args){
        Point p1=new Point(1,1);
        TAngle t=new TAngle(p1,new Point(5,1),new Point(3,4));
        System.out.println("Triangle area="+t.getArea());
    }
}

两个类相互配合完成任务,对类的认识又更进一步。

上一篇:华为上机:求2的N次幂的值


下一篇:示例:WPF中自定义StoryBoarService在代码中封装StoryBoard、Animation用于简化动画编写