如何检查给定的点是否在线段中?
我一开始用了这个:
if (s == null) { return false; }
if (!(s instanceof Point)) { return false; }
return (x == ((Point) s).x && y == ((Point) s).y);
但它并没有真正起作用,因为 LineSegment 不是一个对象。
这是我到目前为止的代码:
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
}
}
}
编辑:据我所知,这里有一些问题可能与我的相同......我需要的答案不存在。
好吧,假设如果线段由两个点定义:点和起点,这就是测试给定点是否在此线段上的方法:
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);
}