输入学生姓名,Java成绩,按分数从高到低排序后存储在文件score.txt中。
时间: 2024-02-16 07:59:54 浏览: 76
好的,以下是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("请输入学生姓名(输入0结束输入):");
String name = scanner.next();
if ("0".equals(name)) {
break;
}
System.out.print("请输入" + name + "的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();
}
System.out.println("成绩已保存到score.txt文件中");
} catch (IOException e) {
e.printStackTrace();
}
}
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 o.score - this.score;
}
}
}
```
在运行程序后,按照提示输入学生姓名和Java成绩,输入0结束输入。程序会将学生信息按照Java成绩从高到低排序,并将排序结果写入文件score.txt中。
阅读全文
相关推荐
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.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)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)