2013-02-19 45 views
0

我需要实现一个三角形类,并坚持比较边的长度来确定三角形是否确实是等腰。以下是我迄今为止:实现类,三角形等腰

public class TriangleIsosceles { 

    private Point cornerA; 
    private Point cornerB; 
    private Point cornerC; 
    private int x1; 
    private int y1; 
    private int x2; 
    private int y2; 
    private int x3; 
    private int y3; 

    public TriangleIsosceles(){ 
     cornerA = new Point(0,0); 
     cornerB = new Point(10,0); 
     cornerC = new Point(5,5); 
    } 

    public TriangleIsosceles(int x1,int y1,int x2,int y2,int x3,int y3){ 
     cornerA = new Point(x1,y1); 
     cornerB = new Point(x2,y2); 
     cornerC = new Point(x3,y3); 
    } 

    public String isIsosceles(String isIsosceles){ 
     return isIsosceles; 
    } 

} 

使用Point物体IM是这样的:

public class Point { 

    private int x; 
    private int y; 

    public Point(){ 
     this(0,0); 
    } 

    public Point(int x, int y){ 
     this.x = x; 
     this.y = y; 
    } 
    public void setX(int x){ 
     this.x=x; 
    } 
    public void setY(int y){ 
     this.y=y; 
    } 
    public void printPoint(){ 
     System.out.println(x + y); 
    } 

    public String toString(){ 
     return "x = "+x+" y = "+y; 
    } 

} 

在另一类(LineSegment)我创建了一个方法length()确定的两个点之间的距离。它看起来像:

public double length() { 
    double length = Math.sqrt(Math.pow(x1-x2,2) + Math.pow(y1-y2,2)); 
    return length; 
} 

我怎么可以用这种方法来帮助我找到了三角形的长度在我TriangleIsosceles类?

我知道我需要看看(lenghtAB == lengthBC || lengthBC == lenghtCA || lengthAB == lengthCA)

回答

1

快速,完全有效的,解决办法是让你的长度方法的静态实用方法,即

public static double length(x1, y1, x2, y2) 
{ 
    return Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2)); 
} 

or 

public static double length(Point p1, Point p2) 
{ 
    return Math.sqrt(Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2)); 
} 

您还可以添加方法,以点本身,即在点类中添加:

public double calcDistance(Point otherPoint) 
{ 
    return Math.sqrt(Math.pow(this.x - otherPoint.x, 2) + Math.pow(this.y - otherPoint.y, 2)); 
} 
+0

[Point2D#distance(Point2D)](http://docs.oracle.com/javase/7/docs/api/java/awt/geom/Point2D.html#distance(java.awt.geom.Point2D) )看起来好像很容易,不是吗? – 2013-02-19 00:50:07

+0

是的,这就是我最有可能实现它的方式,也是我作为第三种解决方案展示的内容。我不想给出几个替代方案进行比较。 – DSJ 2013-02-19 01:01:41

+0

它已经在那里了。在java.awt.Point类中... – 2013-02-19 01:09:22

0

假设你LineSegment类有一个构造函数,需要两个Point对象,你应该创建三个LineSegment对象(你可以在Triangle级高速缓存)。然后使用LineSegment#getLength()您可以确定是否有任何两边的长度相同。

由于这看起来像作业,我不会给你完整的解决方案。