java编程:输入n个二维平面上的坐标点,所有的坐标点按照以x轴数为第一关键字,y轴为第二关键字顺

java编程:输入n个二维平面上的坐标点,所有的坐标点按照以x轴数为第一关键字,y轴为第二关键字顺序从小到大排序,输入说明:输入一个点的个数n个,然后输入n个二维整数坐标值。输入范例:见图片。谢谢,急!谢谢您!

import java.util.Arrays;
import java.util.Scanner;

public class Demo {

public static void main(String args[]) {
Scanner in = new Scanner(System.in);

int n = in.nextInt();
MyPoint[] points = new MyPoint[n];
for (int i = 0; i < n; i++) {
points[i] = new MyPoint(in.nextInt(), in.nextInt());
}
Arrays.sort(points);

//System.out.println("排序后:");
for (int i = 0; i < n; i++) {
System.out.println(points[i].x + " " + points[i].y);
}

in.close();
}

}

class MyPoint implements Comparable<MyPoint> {

public int x;
public int y;

public MyPoint(int x, int y) {
this.x = x;
this.y = y;
}

@Override
public int compareTo(MyPoint other) {
if (this.x > other.x) {
return 1;
} else if (this.x < other.x) {
return -1;
} else if (this.y > other.y) {
return 1;
} else if (this.y < other.y) {
return -1;
}
return 0;
}

}

运行示例:

追问

你运行了啊

看不明白
能稍微解释一下吗 谢谢哦

追答

就是说定义一个类 MyPoint,它包含 x 和 y 两个值。这个类实现了 Comparable<MyPoint> 接口,<MyPoint> 表示比较的时候是 当前实例和另一个 MyPoint 的实例进行比较。比较的规则就是下面的代码:

if (this.x > other.x) {
return 1;
    } else if (this.x < other.x) {
     return -1;
    } else if (this.y > other.y) {
     return 1;
    } else if (this.y < other.y) {
     return -1;
    }
    return 0;
}

这个规则就是你题目要的那个效果。

然后 Arrays.sort 方法可以对实现了Comparable 接口的类对数组进行排序,根据 compareTo 方法来排(我们自己在这个方法里定义的排序规则)。

追问

好的 谢谢你哦

你能稍微跟我讲一下comparable《mypoint》接口是什么意思吗?我还没学到那里 谢谢

我的有错误啊?

温馨提示:答案为网友推荐,仅供参考