编写一个java程序,实现一下功能,要求 设计一个学生student类,包含学号、姓名、出生日期、性别等字段 从input.txt(从附件下载)中读取其中的学生信息,并存入学生集合list中 对学生集合list进行排序,按照出生日期从早到晚排序(即年龄由大到小) 将排序后的学生集合list输出到output.txt文件中,输出格式同input.txt:一行一个学生,依次输出学号、姓名、出生日期、性别并用空格隔开
时间: 2024-02-15 13:01:43 浏览: 85
好的,根据您的要求,我为您编写了以下 Java 程序。请注意,代码中的注释会帮助您理解程序的工作原理。
```java
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;
class Student {
private int id; // 学号
private String name; // 姓名
private int birthYear; // 出生年份
private int birthMonth; // 出生月份
private int birthDay; // 出生日期
private String gender; // 性别
public Student(int id, String name, int birthYear, int birthMonth, int birthDay, String gender) {
this.id = id;
this.name = name;
this.birthYear = birthYear;
this.birthMonth = birthMonth;
this.birthDay = birthDay;
this.gender = gender;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getBirthYear() {
return birthYear;
}
public int getBirthMonth() {
return birthMonth;
}
public int getBirthDay() {
return birthDay;
}
public String getGender() {
return gender;
}
@Override
public String toString() {
return id + " " + name + " " + birthYear + "-" + birthMonth + "-" + birthDay + " " + gender;
}
}
class StudentComparator implements Comparator<Student> {
@Override
public int compare(Student s1, Student s2) {
// 按出生日期从早到晚排序
if (s1.getBirthYear() != s2.getBirthYear()) {
return s1.getBirthYear() - s2.getBirthYear();
} else if (s1.getBirthMonth() != s2.getBirthMonth()) {
return s1.getBirthMonth() - s2.getBirthMonth();
} else {
return s1.getBirthDay() - s2.getBirthDay();
}
}
}
public class Main {
public static void main(String[] args) {
// 读取 input.txt 中的学生信息,存入学生集合 list 中
ArrayList<Student> list = new ArrayList<>();
try {
File inputFile = new File("input.txt");
Scanner scanner = new Scanner(inputFile);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] fields = line.split(" ");
int id = Integer.parseInt(fields[0]);
String name = fields[1];
String[] birthFields = fields[2].split("-");
int birthYear = Integer.parseInt(birthFields[0]);
int birthMonth = Integer.parseInt(birthFields[1]);
int birthDay = Integer.parseInt(birthFields[2]);
String gender = fields[3];
Student student = new Student(id, name, birthYear, birthMonth, birthDay, gender);
list.add(student);
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// 对学生集合 list 进行排序
Collections.sort(list, new StudentComparator());
// 将排序后的学生集合 list 输出到 output.txt 文件中
try {
FileWriter writer = new FileWriter("output.txt");
for (Student student : list) {
writer.write(student.toString() + "\n");
}
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
请将上述代码保存为 Main.java 文件,并将 input.txt 文件放在同一目录下。运行程序后,它会自动读取 input.txt 文件中的学生信息,按照出生日期从早到晚排序,并将排序后的学生集合输出到 output.txt 文件中。
阅读全文