用java编写输入学生姓名,Java成绩,按分数从高到低排序后存储在文件score.txt中。
时间: 2023-07-16 16:13:17 浏览: 114
以下是一个示例代码,实现输入学生姓名和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 (PrintWriter writer = new PrintWriter(new FileWriter("score.txt"))) {
for (Student student : students) {
writer.println(student.getName() + " " + student.getScore());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
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 other) {
return Integer.compare(other.score, this.score);
}
}
```
运行程序后,输入学生姓名和Java成绩,程序会将数据按照成绩从高到低排序,并将排序后的数据存储到文件score.txt中。
阅读全文