Add the following method to the Point class: public boolean isCollinear(Point p1
ID: 3530558 • Letter: A
Question
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 special-cased 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. public class Point { private int x; private int y; // your code goes here }Explanation / Answer
public class point {private int x; private int y; public boolean isCollinear(Point p1,Point p2) { float d1=sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y)); float d2=sqrt((this->x-p1.x)*(this->x-p1.x)+(this->y-p1.y)*(this->y-p1.y)); float d3=sqrt((this->x-p2.x)*(this->x-p2.x)+(this->y-p2.y)*(this->y-p2.y)); if(findlargest(d1,d2,d3)==d3)){if(d1+d2==d3)return true;} if(findlargest(d1,d2,d3)==d2)){if(d1+d3==d2)return true;} if(findlargest(d1,d2,d3)==d1)){if(d3+d2==d1)return true;} return false; } public int findlargest(float p,float q,float r) {if(p>=q){ if(p>r)return p;else return r;} if(q>=p){if(q>r)return q;else return r;} } }
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.