Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a program that meets the following requirements: Define a class named Poin

ID: 639255 • Letter: W

Question

Write a program that meets the following requirements:

Define a class named Point with two data fields x and y to represent a point's x and y coordinates.

Define two classes CompareX and CompareY that implement Comparator<Point>. For CompareX, compare points using the x-coordinates. If the x-coordinates are equal, then use the y-coordinates. For CompareY, compare points using the y-coordinates. If the y-coordinates are equal, then use the x-coordinates.

Randomly create 100 points and sort these points twice: once using CompareX and the other using CompareY.

Explanation / 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;
}
}

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote