定义一个birthday类,包括年,月,日三个成员变量。默认创建一个“2000-01-01”的对象,否则按照提供的日期字符串创造对象。birthday类中定义一个排序成员方法public boolean sort(Birthday birthnew),可以实现按年龄排序的操作。输入n(n<10)个人的生日信息,按照年龄大小顺序输出。用java写
时间: 2024-02-05 11:13:44 浏览: 139
以下是代码实现:
```
import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
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 birthdayStr) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate date = LocalDate.parse(birthdayStr, formatter);
this.year = date.getYear();
this.month = date.getMonthValue();
this.day = date.getDayOfMonth();
}
public boolean sort(Birthday birthnew) {
return this.compareTo(birthnew) < 0;
}
public int getAge() {
LocalDate today = LocalDate.now();
LocalDate birthday = LocalDate.of(year, month, day);
return Period.between(birthday, today).getYears();
}
@Override
public int compareTo(Birthday o) {
int ageDiff = this.getAge() - o.getAge();
if (ageDiff != 0) {
return ageDiff;
} else if (this.year != o.year) {
return this.year - o.year;
} else if (this.month != o.month) {
return this.month - o.month;
} else {
return this.day - o.day;
}
}
@Override
public String toString() {
return String.format("%04d-%02d-%02d", year, month, day);
}
}
```
在主函数中,我们可以按照以下方式输入生日信息并排序输出:
```
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("请输入人数:");
int n = input.nextInt();
Birthday[] birthdays = new Birthday[n];
for (int i = 0; i < n; i++) {
System.out.printf("请输入第%d个人的生日(格式为yyyy-MM-dd):", i + 1);
String birthdayStr = input.next();
birthdays[i] = new Birthday(birthdayStr);
}
Arrays.sort(birthdays);
System.out.println("按年龄从小到大排序后的生日信息:");
for (Birthday birthday : birthdays) {
System.out.println(birthday);
}
}
}
```
阅读全文