Java 实现类、三角形等腰线
我需要实现一个三角形类,我一直在比较边的长度,以确定三角形是否确实是等腰三角形。以下是我到目前为止的情况:Java 实现类、三角形等腰线,java,geometry,implementation,Java,Geometry,Implementation,我需要实现一个三角形类,我一直在比较边的长度,以确定三角形是否确实是等腰三角形。以下是我到目前为止的情况: public class TriangleIsosceles { private Point cornerA; private Point cornerB; private Point cornerC; private int x1; private int y1; private int x2; private int y2;
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;
}
}
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;
}
如何使用此方法帮助我在TriangleIsoCeles
类中查找三角形的长度
我知道我需要看看是否
(lenghtAB==lengthBC | | lengthBC==lenghtCA | | lengthAB==lengthCA)
假设您的LineSegment
类有一个接受两个Point
对象的构造函数,您应该创建三个LineSegment
对象(您可以将其缓存在Triangle
类中)。然后使用LineSegment#getLength()
可以确定任意两条边的长度是否相同
因为这看起来像是家庭作业,所以我不会给你完整的答案 一个快速、完全有效的解决方案是将长度方法变成静态实用方法,即
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));
}
您还可以将该方法添加到Point本身,即在Point类中添加:
public double calcDistance(Point otherPoint)
{
return Math.sqrt(Math.pow(this.x - otherPoint.x, 2) + Math.pow(this.y - otherPoint.y, 2));
}
[Point2D#distance(Point2D)](看起来要容易得多,不是吗?是的,这是我最有可能实现它的方式,这是我在上面展示的第三个解决方案。我只是想给出一些备选方案以供比较。