java输入学生姓名,Java成绩,按分数从高到低排序后存储在文件score.txt中。
时间: 2023-11-27 14:50:02 浏览: 200
以下是一个示例代码,实现了输入学生姓名和Java成绩,并按照成绩从高到低排序后存储在文件score.txt中。
```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<Student>();
// 输入学生信息
while (true) {
System.out.print("请输入学生姓名:");
String name = scanner.next();
if (name.equals("exit")) {
break;
}
System.out.print("请输入Java成绩:");
int score = scanner.nextInt();
Student student = new Student(name, score);
students.add(student);
}
// 按照成绩从高到低排序
Collections.sort(students);
// 写入文件
try {
FileWriter writer = new FileWriter("score.txt");
for (Student student : students) {
writer.write(student.getName() + " " + student.getScore() + "\n");
}
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("已将学生成绩按照从高到低的顺序保存在score.txt文件中。");
}
}
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 other.score - this.score;
}
}
```
在上述代码中,通过Scanner读取用户输入的学生信息,并将其存储在List<Student>中。然后使用Collections.sort方法按照成绩从高到低排序,最后将结果写入score.txt文件中。注意,在Student类中实现了Comparable接口,以便在排序时比较学生的成绩。
阅读全文