java将所有人的成绩排序写入到一个新文件成绩从高往低排序姓名靠左对,分数靠右对齐。
时间: 2023-05-18 21:06:26 浏览: 91
可以使用Java的Collections.sort()方法对成绩进行排序,然后使用FileWriter将排序后的成绩写入到一个新文件中。对于姓名靠左对齐,可以使用String.format()方法进行格式化输出,例如:String.format("%-10s", name),其中10表示输出的字符串长度,左对齐使用"-"标记。对于分数靠右对齐,可以使用String.format()方法的"%10d"格式化输出,其中10表示输出的字符串长度,右对齐不需要使用标记。完整代码如下:
```
import java.io.*;
import java.util.*;
public class ScoreSorter {
public static void main(String[] args) throws IOException {
// 读取成绩文件
Scanner scanner = new Scanner(new File("scores.txt"));
List<Student> students = new ArrayList<>();
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] parts = line.split("\\s+");
String name = parts[0];
int score = Integer.parseInt(parts[1]);
students.add(new Student(name, score));
}
scanner.close();
// 排序
Collections.sort(students);
// 写入新文件
FileWriter writer = new FileWriter(new File("sorted_scores.txt"));
for (Student student : students) {
String name = student.getName();
int score = student.getScore();
String line = String.format("%-10s%10d\n", name, score);
writer.write(line);
}
writer.close();
}
}
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;
}
}
```