用Java定义一个 birthday 类,包括年、月、日三个成员变量。默认创建一个"2000-01-01"的对象,否则按照提供的日期字符串创建对象。 birthday 类中定义一个排序成员方法 public boolean sort ( Birthday birthnew ),可以实现按年龄排序的操作。输入 n ( n <10)个人的生日信息,按照年龄大小顺序输出。
时间: 2024-02-05 21:12:34 浏览: 32
以下是Java实现:
```java
import java.time.LocalDate;
import java.time.Period;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Birthday implements Comparable<Birthday> {
private int year;
private int month;
private int day;
public Birthday() {
this.year = 2000;
this.month = 1;
this.day = 1;
}
public Birthday(String dateStr) {
String[] parts = dateStr.split("-");
this.year = Integer.parseInt(parts[0]);
this.month = Integer.parseInt(parts[1]);
this.day = Integer.parseInt(parts[2]);
}
public boolean sort(Birthday other) {
return compareTo(other) < 0;
}
@Override
public int compareTo(Birthday other) {
LocalDate date1 = LocalDate.of(year, month, day);
LocalDate date2 = LocalDate.of(other.year, other.month, other.day);
Period period = Period.between(date1, date2);
return period.getYears();
}
public static void main(String[] args) {
List<Birthday> birthdays = new ArrayList<>();
birthdays.add(new Birthday("2001-05-06"));
birthdays.add(new Birthday("1999-10-12"));
birthdays.add(new Birthday("2002-03-25"));
Collections.sort(birthdays);
for (Birthday birthday : birthdays) {
System.out.println(birthday.year + "-" + birthday.month + "-" + birthday.day);
}
}
}
```
首先定义了一个 `Birthday` 类,包含年、月、日三个成员变量。默认创建一个"2000-01-01"的对象,否则按照提供的日期字符串创建对象。
其中,`sort` 方法实现了按照年龄排序的操作,使用了 `compareTo` 方法比较两个 `Birthday` 对象的年龄大小。
在 `main` 方法中,我们创建了一个 `List` 对象来存储 `Birthday` 对象,并使用 `Collections.sort` 方法按照年龄大小进行排序。最后输出排序后的结果。
你可以根据需要修改代码,例如修改日期格式或者输入方式。