Recall that Coordinate is a class defined with two double variables x and y repr
ID: 3778802 • Letter: R
Question
Recall that Coordinate is a class defined with two double variables x and y representing the (x,y)-coordinate od a point on the xy plane. Suppose two coordinates c=(x,y) and c'(x",y') are compared to each other as follows: 1. c is smaller than c' if ether x<x' or (x =x' and y<y'), 2. c is equal to c' if x = x' and y = y', and 3. c is greater than c' if either x>x' and y>y'. According to this rule, write an instance method public int compareTo(Coordinate o) that compares this with o that returns -1,0,+!, respectively to the above three cases.
Explanation / Answer
import java.lang.*;
class Coordinate {
double x;
double y;
public Coordinate(double a,double b){
x=a;
y=b;
}
public int compareTo(Coordinate o)
{
/* return 0 if both coordinates are equal */
/* return -1 if 'o' coordinate is less than the class coordinate */
/* return 1 if 'o' coordinate is greater
if( Double.compare(o.x,x) == 0 && Double.compre(o.y,y)==0){
return 0;
}
else if((Double.compare(o.x,x)<0 && Double.compare(o.y,y)<0)||((Double.compare(o.x,x)=0 && Double.compare(o.y,y)<0))
{
return 1;
}else if((Double.compare(o.x,x)>0 && Double.compare(o.y,y)>0)){
return -1;
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.