2013-02-19 43 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()您可以確定是否有任何兩邊的長度相同。

由於這看起來像作業,我不會給你完整的解決方案。