## Question

public Line(Point p1, Point p2)

Constructs a new line that contains the given two points.

public Point getP1()

Returns this line's first endpoint.

public Point getP2()

Returns this line's second endpoint.

public String toString()

Returns a string representation of this line, such as "[(22, 3), (4, 7)]".

Add the following method to your Line class from the previous exercise:

public double getSlope()

Returns the slope of this line. The slope of a line between points (x1, y1) and (x2, y2) is equal to (y2 - y1) / (x2 - x1). If the two points have the same x-coordinates, the denominator is zero and the slope is undefined, so you should throw an IllegalStateException in this case.

Add the following constructor to your Line class from the preceding exercises:

public Line(int x1, int y1, int x2, int y2)

Constructs a new line that contains the given two points.

Add the following method to your Line class:

public boolean isCollinear(Point p)

Returns true if the given point is collinear with the points of this line; that is, if, when this Line is stretched infinitely, it would eventually hit the given point. Points are collinear if a straight line can be drawn that connects them. Two basic examples are three points that have the same x- or y-coordinate. The more general case can be determined by calculating the slope of the line between each pair of points and checking whether this slope is the same for all pairs of points. Use the formula (y2 - y1) / (x2 - x1) to determine the slope between two points (x1, y1) and (x2, y2).

(Note that this formula fails for points with identical x-coordinates, so this will have to be a special case in your code.) Since Java's double type is imprecise, round all slope values to four digits past the decimal point before you compare them.

## Solution Preview

These solutions may offer step-by-step problem-solving explanations or good writing examples that include modern styles of formatting and construction of bibliographies out of text citations and references. Students may use these solutions for personal skill-building and practice. Unethical use is strictly forbidden.

public class Line {Point p1;

Point p2;

/**

* constructor

* Constructs a new line that contains

* the given two points.

* @param p1

* @param p2

*/

public Line(Point p1, Point p2) {

this.p1 = p1;

this.p2 = p2;

}

/**

* constructor

* Constructs a new line that

* contains the given two points.

* @param x1

* @param y1

* @param x2

* @param y2

*/

public Line(int x1, int y1, int x2, int y2) {

p1 = new Point(x1, y1);

p2 = new Point(x2, y2);

}

/**

* Returns this line's first endpoint.

* @return point1

*/

public Point getP1() {

return p1;

}...

By purchasing this solution you'll be able to access the following files:

SolutionDriver.java and SolutionLine.java.