用java写程序,2.对一个运动会成绩原始文件“results.txt”,对运动员的竞赛成绩进行排名,将结果按格式保存到输出文件“out.txt”,成绩保留3位小数。
时间: 2024-02-15 22:01:21 浏览: 24
好的,我可以帮你解决这个问题。你可以参考以下代码:
```java
import java.io.*;
import java.util.*;
public class SortResults {
public static void main(String[] args) {
String inputFileName = "results.txt";
String outputFileName = "out.txt";
List<Athlete> athletes = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(inputFileName))) {
String line;
while ((line = br.readLine()) != null) {
String[] tokens = line.split("\t");
String name = tokens[0];
double time = Double.parseDouble(tokens[1]);
Athlete athlete = new Athlete(name, time);
athletes.add(athlete);
}
} catch (IOException e) {
e.printStackTrace();
}
Collections.sort(athletes);
try (PrintWriter pw = new PrintWriter(new FileWriter(outputFileName))) {
int rank = 1;
for (Athlete athlete : athletes) {
pw.printf("%d\t%s\t%.3f\n", rank, athlete.getName(), athlete.getTime());
rank++;
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static class Athlete implements Comparable<Athlete> {
private String name;
private double time;
public Athlete(String name, double time) {
this.name = name;
this.time = time;
}
public String getName() {
return name;
}
public double getTime() {
return time;
}
@Override
public int compareTo(Athlete o) {
return Double.compare(time, o.time);
}
}
}
```
这个程序首先读取“results.txt”文件中的数据,然后创建一个Athlete对象的列表。然后使用Collections.sort()方法对该列表进行排序,排序依据是运动员的竞赛成绩。最后,程序将排序结果写入“out.txt”文件中。