Add the following method to the Point class:
public boolean isCollinear(Point p1, Point p2)
Returns whether this Point is collinear with the given two other Points. 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 a reasonable accuracy such as four digits past the decimal point before you compare them.
Point class
//package classes;
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;
}
public boolean isCollinear(Point p1, Point p2) {
// return true if x or y coordinates are same in three points
if(this.x == p1.x || this.x == p2.x)
return this.x == p1.x && this.x == p2.x;
if(this.y == p1.y || this.y == p2.y)
return this.y == p1.y && this.y == p2.y;
// formula to calclate slope
//(y2-y1)/(x2-x1)
double slope1 = ((double) (this.y - p1.y)) / (this.x - p1.x);
double slope2 = ((double) (this.y - p2.y)) / (this.x - p2.x);
if(slope1 == slope2)
return true;
return false;
}
}
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 = 3;
Point p2 = new Point();
p2.x = 4;
p2.y = 3;
Point p3 = new Point();
p3.x = 8;
p3.y = 8;
// 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();
// print the points again
// System.out.println("p1 is (" + p1.x + ", " + p1.y + ")");
// System.out.println("p2 is (" + p2.x + ", " + p2.y + ")");
System.out.println("p1 is (" + p1.x + ", " + p1.y + ")");
System.out.println("p2 is (" + p2.x + ", " + p2.y + ")");
System.out.println("p3 is (" + p3.x + ", " + p3.y + ")");
boolean isCollinear = p1.isCollinear(p2, p3);
System.out.println("\nare the three points are in collinear: " +isCollinear);
}
}
Output:
p1 is (7, 3)
distance from origin = 7.615773105863909
p2 is (4, 3)
distance from origin = 5.0
p1 is (7, 3)
p2 is (4, 3)
p3 is (8, 8)
are the three points are in collinear: false