Add the following method to your Line class:
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 x2 equals x1 the denominator is zero and the slope is undefined, so you may throw an exception in this case.
// package classes;
public class Line {
Point point1;
Point point2;
// create constructor to initiate the line class
public Line(Point Point1, Point point2) {
this.point1 = Point1;
this.point2 = point2;
}
// methods to get point1 and poit 2
public Point getPoint1() {
return point1;
}
public Point getPoint2() {
return point2;
}
public String toString() {
return "[" +point1.toString()+", " +point2.toString()+"]";
}
// method to get slope
public double getSlope() {
if(point1.getX() == point2.getX())
throw new IllegalArgumentException();
double slope = (double) (point2.getY() - point1.getY()) / (point2.getX() - point1.getX());
return slope;
}
// driver method
public static void main(String[] args) {
Point point1 = new Point(3,6);
Point point2 = new Point(7,8);
Line line = new Line(point1,point2);
System.out.println("the string representation of the line is :"+line);
System.out.println("slope of the line is: " +line.getSlope());
}
}
Output: the string representation of the line is :[(3,6), (7,8)] slope of the line is: 0.5