Question: Define three classes to represent sloped line, horizontal line, and vertical line and they must implement the Line interface. Implement distanceTo(Point p) method for the

Define three classes to represent sloped line, horizontal line, and

vertical line and they must implement the Line interface.

Implement distanceTo(Point p) method for the three classes so that

it returns the shortest distance from the line to the point p. Also implement

nearestPointTo(Point p) to return the nearest point on this line to p.

------------------------------------------------------------------------------------------------------

class Point {

final double x,y; // x, y coordinate of a point

Point(int x, int y) {

this.x = x;

this.y = y;

}

double distanceTo(Point p) {

return Math.sqrt(Math.pow(x-p.x, 2) + Math.pow(y-p.y, 2));

}

}

interface Line {

Point nearestPointTo (Point p);

double distanceTo (Point p);

}

// Define class SlopedLine, HorizontalLine, and VerticalLine

// that implement Line interface

// HorizontalLine only needs to know the y coordinate of the points

// VerticalLine only needs to know the x coordinate of the points

// SlopedLine will store its slope m and intercept k

// Make sure you also define a method "Point nearestPointTo(Point p)"

// to return the nearest point on this line to p

-----------------------------------------------------------------------------------------------------

The two points for a horizontal line has the same y coordinates. The shortest

distance from the horizontal line to a point is the difference between their y

coordinates. The two points for a vertical line has the same x coordinates. The

shortest distance from the vertical line to a point is the difference between their

x coordinates.

Given points p1 and p2 for a sloped line, you will and its slope m and

intercept k by

m =p1.y - p2.y / p1.x- p2.x

k = p1.y - m * p1.x

You should store the slope and intercept in the fields of the sloped line object.

Given a line defined by slope m and intercept k, you can finnd its normal line

l that passes the point p by

ml = 1=m

kl = p.y - ml * p:x

where ml and kl is the slope and intercept of the normal line l.

Next step is to find the intersection point pl between this line and its normal

line l. The x, y coordinates of pl is defined by

x = (l.k - k)=(m l.m)

y = m * x + k

The smallest distance from this line to the point p is the distance between pl to p. Also, pl is the nearest point to p.

----------------------------------------------------------

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!