如何检查给定点是否在线段中?

时间:2016-01-16 17:48:54

标签: java boolean line point line-segment

如何检查给定点是否在线段中?

我最初使用过这个:

if (s == null) { return false; }
if (!(s instanceof Point)) { return false; }
return (x == ((Point) s).x && y == ((Point) s).y); 

但它确实不起作用,因为LineSegment不是Object ..

到目前为止,这是我的代码:

public class Point {

    double x;
    double y;   

    public Point(double x, double y) {

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

    public Line straightThrough (Point p) {
    // TODO 
    }

    public boolean onLineSegment(LineSegment s) {

        if (s == null) {
            return false;
        // TODO
        }
    }
}
编辑:据我所知,这里有一些问题可能跟我的一样......我需要的答案不在那里。

1 个答案:

答案 0 :(得分:0)

好吧,假设某个线段是由两个点定义的:enpoint和startpoint,这就是测试给定点是否在此线段上的方法:

boolean     isOnLineSegment(LineSegment seg, Point test) {

return  (   (test.y-seg.startPoint.y)/(test.x-seg.startPoint.x) == (test.y-seg.endPoint.y)/(test.x-seg.endPoint.y);

}
相关问题