announcements‎ > ‎

2015-09-30

posted Sep 30, 2015, 4:55 AM by Samuel Konstantinovich   [ updated Oct 1, 2015, 6:28 AM ]
Notes and completed Triangle:

public class Triangle{
    private Coordinate v1, v2, v3;

    //DEFAULT CONSTRUCTOR WILL NOT WORK IF YOU LEAVE IT EMPTY
    //Your coordinates would be null, and your methods will not
    //work properly (null pointer exceptions)
    public Triangle(){
	v1 = new Coordinate(0,0);
	v2 = new Coordinate(1,0);
	v3 = new Coordinate(0,1);
    }
    
    public Triangle(Coordinate a,Coordinate b,Coordinate c){
	v1 = new Coordinate(a.getX(),a.getY());//make a copy of a with the 
	//same values of x and y, put into a new object
	v2 = b;//either do what you did in v1, or do the same as v2 and v3
	v3 = c;//do not mix how you initialize the vertices.
    }

    public Triangle(double x1,double y1,double x2,double y2,double x3,double y3){
	v1 = new Coordinate(x1,y1);
	v2 = new Coordinate(x2,y2);
	v3 = new Coordinate(x3,y3);
    }
    public String toString(){
	return "Triangle:" + v1 + v2 + v3;
    }

    public double getPerimeter(){
	return v1.dist(v2) + v2.dist(v3) + v3.dist(v1);
    }

    public double getArea(){
	double semip = getPerimeter() / 2 ;  
	return Math.sqrt(
			 semip *
			 (semip - v1.dist(v2)) * 
			 (semip - v2.dist(v3)) * 
			 (semip - v3.dist(v1)) );
    }

    private boolean closeEnough(double a,double b){
	return (a - b)/b < 0.00000000001;
    }

    private boolean pycheck(Coordinate a, Coordinate b, Coordinate c){
	double s1,s2,s3;
        s1 = a.dist(b);
        s2 = a.dist(c);
        s3 = b.dist(c);
        //if we write this correctly then isRight will work too!
        return s1*s1 + s2*s2 == s3*s3; //this will fail because of floating point rounding error.
	//return closeEnough(s1*s1 + s2*s2 , s3*s3);
    }

    public boolean isRight(){
        return pycheck(v1,v2,v3) || 
               pycheck(v2,v3,v1) || 
               pycheck(v3,v1,v2);
    }

}
Comments