定义一个工具函数用于从文件读取所有学生信息,创建学生数组。

要求:

1
2
3
4
5
6
7
8
9
public class Student {
public static Student[] readFromFile(String path, int num) {
// 使用FileReader读取文件,设置路径参数;
// 使用BufferedReader对FileReader进行装饰,支持按行读取的readLine()方法
// 循环读取每一行数据,一行代表一个学生信息:(line = br.readLine()) != null
// 使用String.split(",")方法将每行数据分割为数组,根据索引获取对应字段值来初始化Student对象
// 返回学生对象数组
}
}

写法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public static Student[] readFromFile(String path, int num) {
Student[] students = new Student[num];
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
String line;
int index = 0;
while ((line = br.readLine()) != null && index < num) {
// 假设每行数据格式为:name,age,grade
String[] parts = line.split(",");
if (parts.length == 3) {
String name = parts[0].trim();
int age = Integer.parseInt(parts[1].trim());
String grade = parts[2].trim();
students[index++] = new Student(name, age, grade);
}
}
} catch (IOException e) {
System.err.println("Error reading file: " + e.getMessage());
}
return students;
}

尝试用Files和Paths读取文件,实现读取文件的功能。

要求:

1
2
3
4
5
6
7
8
public class Student {
public static Student[] readFromFile(String path, int num) {
// Files.readAllLines(Paths.get(path))来读取所有行
// for(String line : lines)来遍历List中的每一行
// 使用String.split(",")方法将每行数据分割为数组,根据索引获取对应字段值来初始化Student对象
// 返回学生对象数组
}
}

写法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public static Student[] readFromFile(String path, int num) {
Student[] stu = new Student[0];
try {
List<String> lines = Files.readAllLines(Paths.get(path));
stu = new Student[Math.min(num,lines.size())];
int index = 0;

for (String line : lines) {
if (index >= num) break;
String[] parts = line.split(",");
String id = parts[0];
int scoreA = Integer.parseInt(parts[1]);
int scoreB = Integer.parseInt(parts[2]);
int scoreC = Integer.parseInt(parts[3]);
stu[index] = new Student(id, scoreA, scoreB, scoreC);
index++;
}
} catch (IOException e) {
System.out.println(e);
}

return stu;
}

排序函数

1
2
3
4
5
6
public class Student {
public static void sortByTotalScore(Student[] s) {
// 实现一个基于总分比较的Comparator接口
Arrays.sort(s, c);
}
}

附上要求的Comparator接口实现

1
2
3
4
5
6
7
// Comparator 实现
public static final Comparator<Student> c = new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
return Double.compare(s2.getTotalScore(), s1.getTotalScore()); // 按总分从高到低排序
}
};

lambda表达式的简写:

1
2
3
public static void sortByTotalScore(Student[] s) {
Arrays.sort(s, Comparator.comparingInt(x -> x.totalScore()));
}