流星也为你落下


私信TA

用户名:dotcpp0796798

访问量:31

签 名:

我会意气风发

等  级
排  名 5938
经  验 1459
参赛次数 0
文章发表 12
年  龄 20
在职情况 学生
学  校 江西理工大学
专  业 软件工程

  自我简介:

解题思路:

从用户输入中读取日期字符串,将其解析为自定义的 MyDate 对象,然后将这些日期进行排序并输出

注意事项:    使用 while 循环读取输入的日期字符串时:

                * 将输入的字符串按“/”分割成三个部分,并将其转换为整数以构造 MyDate 对象。

                * 检查当前数组是否已满,如果满了则使用 Arrays.copyOf 方法扩容数组。  

                * 将新创建的 MyDate 对象添加到数组中,并增加计数器 i 。

                * 要在自定义类中实现Comparable接口,同时重写compareTo()方法
参考代码:

import java.util.*;


public class Main {

public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        MyDate[] myDates  = new MyDate[2];


        int i = 0;

        while (scanner.hasNext()){

            String next = scanner.next();

            String[] split = next.split("/");

            //分割成三个字符串再转成对应的int类型进行构造

            MyDate myDate = new MyDate(Integer.parseInt(split[2]), Integer.parseInt(split[0]), Integer.parseInt(split[1]));

            //判断数组大小是否溢出

            if (i >= myDates.length) {

                //数组扩容 —— 建议一个大小一个大小扩容,不然数组中如果有空闲空间进行排序的话回报空指针异常

                MyDate[] newMyDate = Arrays.copyOf(myDates, i + 1);

                myDates = newMyDate;    //再将myDates指向新的空间

            }

            myDates[i++] = myDate;

        }

        //排序

        Arrays.sort(myDates);

        //遍历  —— 这个i的大小就是当前数组的真实长度

        for (int j = 0; j < i; j++) {

            System.out.println(myDates[j]);

        }

    }

}


//单独定义一个日期类,用于日期的比较

class MyDate implements Comparable<MyDate>{

    private int year;

    private int month;

    private int day;


    public MyDate() {

    }

    public MyDate(int year, int month, int day) {

        this.year = year;

        this.month = month;

        this.day = day;

    }


    @Override

    public int compareTo(MyDate o) {

        if (this == null || o == null) return 0;

        if (this.year - o.year != 0) return year - o.year;

        //说明两者的年份相同

        else {

            if (this.month - o.month != 0) return month - o.month;

            //说明两者年份和月份都相同

            else {

                return day - o.day;

            }

        }

    }


    @Override

    public String toString() {

        String newDay = day + "";String newMonth = month +"";

        if (day < 10) {

            newDay = "0"+day ;

        }

        if (month < 10) {

            newMonth = "0" + month;

        }


        return newMonth + "/" + newDay + "/" + year;

    }

}



 

0.0分

1 人评分

  评论区

  • «
  • »