Search code examples
javabooleanlinepointline-segment

How to check whether the given points are in the line segment or not?


How to check whether the given points are in the line segment or not?

I used this at first:

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

but it didn't really work, because LineSegment is not an Object..

This is my code so far:

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
        }
    }
}

EDIT: As I know that there are some questions on here that may be the same as mine... the answer I needed wasn't there.


Solution

  • Well, assuming if a line segment is defined by two points: enpoint and startpoint, this is how you can test if a given point is on this line segment:

    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);
    
    }