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

本文介绍了一个Java程序,该程序接收用户输入的多个二维坐标点,并按照x轴和y轴数值进行排序。首先读取点的数量,然后逐一读取每个点的坐标,使用自定义的MyPoint类存储坐标并实现Comparable接口以支持排序。最后,利用Arrays.sort方法对坐标点进行排序,并输出排序后的结果。

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值