Java - Point on line

2019-07-17 08:18发布

问题:

How can i find out if a Point(x,y) is on a the Line created between two other Points? I tried this but something seems to be wrong, as i don't get the results i should.

public boolean intersects(Point k, Point z, Point p) {

        Line2D line = new Line2D.Float(k.x, k.y, z.x, z.y);

        if (line.ptLineDist(p) == 0) {
            return true;
        } else {
            return false;
        }

    }

回答1:

Try this, taking Hovercraft's note about floating point numbers' imprecision into account.

public boolean intersects(Point k, Point z, Point p) {
       return new Line2D.Float(k, z).ptLineDist(p) <= 0.01;
}


标签: java line point