Add the following method to the Point class:
public double slope(Point other)
Returns the slope of the line drawn between this Point and the given other Point. 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 throw an IllegalArgumentException in this case.
Point class
public class Point {
int x;
int y;
public int getX() {
// TODO Auto-generated method stub
return 0;
}
public int getY() {
// TODO Auto-generated method stub
return 0;
}
// this method throws IllegalArgument exception if same x coordinates
public double slope(Point other) {
if(this.x == other.x)
throw new IllegalArgumentException();
double slope = ((double) (this.y - other.y)) / (this.x - other.x);
return slope;
}
}
Main class
package classes;
public class PointMain {
public static void main(String[] args) {
// create two Point objects
Point p1 = new Point();
p1.x = 7;
p1.y = 2;
Point p2 = new Point();
p2.x = 4;
p2.y = 3;
PointMain pm = new PointMain();
// print each point and its distance from the origin
System.out.println("p1 is (" + p1.x + ", " + p1.y + ")");
double dist1 = Math.sqrt(p1.x * p1.x + p1.y * p1.y);
System.out.println("distance from origin = " + dist1);
System.out.println("p2 is (" + p2.x + ", " + p2.y + ")");
double dist2 = Math.sqrt(p2.x * p2.x + p2.y * p2.y);
System.out.println("distance from origin = " + dist2);
System.out.println();
// translate each point to a new location
p1.x += 11;
p1.y += 6;
p2.x += 9;
p2.y += 7;
// print the points again
System.out.println("p1 is (" + p1.x + ", " + p1.y + ")");
System.out.println("p2 is (" + p2.x + ", " + p2.y + ")");
double slope = p1.slope(p2);
System.out.println("\nslope of point p1 and p2 is: " +slope);
}
}
Output:
p1 is (7, 2)
distance from origin = 7.280109889280518
p2 is (4, 3)
distance from origin = 5.0
p1 is (18, 8)
p2 is (13, 10)
slope of point p1 and p2 is: -0.4