输入学生姓名,Java成绩,按分数从高到低排序后存储在文件score.txt中。
时间: 2024-02-17 21:01:23 浏览: 37
好的,下面是Java代码实现:
```java
import java.io.*;
import java.util.*;
public class ScoreSorter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
List<Student> students = new ArrayList<>();
// 输入学生信息
while (true) {
System.out.print("请输入学生姓名(输入exit退出):");
String name = scanner.next();
if (name.equals("exit")) {
break;
}
System.out.print("请输入Java成绩:");
int score = scanner.nextInt();
students.add(new Student(name, score));
}
// 按分数从高到低排序
Collections.sort(students);
// 写入文件
try (BufferedWriter writer = new BufferedWriter(new FileWriter("score.txt"))) {
for (Student student : students) {
writer.write(student.getName() + " " + student.getScore());
writer.newLine();
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("成绩已保存到文件score.txt中!");
}
static class Student implements Comparable<Student> {
private String name;
private int score;
public Student(String name, int score) {
this.name = name;
this.score = score;
}
public String getName() {
return name;
}
public int getScore() {
return score;
}
@Override
public int compareTo(Student o) {
return Integer.compare(o.score, this.score);
}
}
}
```
这段代码先利用 Scanner 从命令行输入学生信息,然后利用 Collections.sort 方法按照分数从高到低排序,最后将结果写入 score.txt 文件。学生信息使用 Student 类封装,实现 Comparable 接口以便能够排序。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)