please solve the problem using Java. (Sort the points in a plane) Write a progra
ID: 3754557 • Letter: P
Question
please solve the problem using Java.
(Sort the points in a plane) Write a program that meets the following requirements: . Define a class named Point with tow data fields x and y to represent a point's x- and y-coordinates. Implement the Comparable interface for the comparing the points on x-coordinates. If two points have the same x-coordinates, compare their y-coordinates Define a class named CompareY that implements Comparator. Implement the compare method to compare two points on their y-coordinates. If two points have the same y-coordinates, compare their x- coordinates . Randomly create 100 points and apply the Arrays.sort method to display the points in increasing order of their x-coordinates, and increasing order of their y-coordinates, respectivelyExplanation / Answer
import java.util.*;
/**
*
* @author Steves
*/
public class MainComparator {
public static void main(String[] args) {
Point p = new Point(1, 2);
List points = new ArrayList();
Random ran = new Random();
for(int i=0;i<100;i++)
points.add(new Point((ran.nextInt( (9 - (-9) ) + 1)+(-9)),(ran.nextInt( (9 - (-9) ) + 1)+(-9)) ));// min =-9, Max =9
Collections.sort(points, new CompareX());
System.out.println("sort based on compareX " + points.toString());
Collections.sort(points, new CompareY());
System.out.println("sort based on CompareY " + points.toString());
}
}
class Point {
int x,y;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public String toString(){
return "("+this.x + " , " + this.y+")";
}
}
class CompareX implements Comparator<Point> {
@Override
public int compare(Point p1, Point p2) {
if(p1.x>p2.x){
return 1;
}else if(p1.x<p2.x){
return -1;
}else if(p1.y>p2.y){
return 1;
}else if(p1.y<p2.y){
return -1;
}else{
return 0;
}
}
}
class CompareY implements Comparator<Point> {
@Override
public int compare(Point p1, Point p2) {
if(p1.y>p2.y){
return 1;
}else if(p1.y<p2.y){
return -1;
}else if(p1.x>p2.x){
return 1;
}else if(p1.x<p2.x){
return -1;
}else{
return 0;
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.