用java写一个程序,对一个运动会成绩原始文件“results.txt”,对运动员的竞赛成绩进行排名,将结果按格式保存到输出文件“out.txt”,成绩保留3位小数。results.txt文件内容为项目:男子100米预决赛 道次 号码 姓名 单位 成绩 备注 1 J2018 张三 计网 14.854 2 J1801 李四 信通 14.127 3 J5901 王五 机关二 13.320 4 J5114 赵六 继续教育 12.290 5 J1700 孙七 戏影 14.374 6 J5505 周八 后勤 15.
时间: 2024-02-21 10:57:13 浏览: 145
好的,以下是Java代码实现:
```java
import java.io.*;
import java.util.*;
public class SportsRanking {
public static void main(String[] args) throws IOException {
File inFile = new File("results.txt");
File outFile = new File("out.txt");
BufferedReader reader = new BufferedReader(new FileReader(inFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(outFile));
String line = null;
List<Athlete> athletes = new ArrayList<>();
while ((line = reader.readLine()) != null) {
String[] fields = line.split(" ");
String event = fields[0];
int lane = Integer.parseInt(fields[1]);
String number = fields[2];
String name = fields[3];
String unit = fields[4];
double score = Double.parseDouble(fields[5]);
Athlete athlete = new Athlete(event, lane, number, name, unit, score);
athletes.add(athlete);
}
Collections.sort(athletes);
int rank = 1;
for (Athlete athlete : athletes) {
writer.write(String.format("%-8s%-6d%-8s%-8s%-8s%.3f\n",
athlete.getEvent(), athlete.getLane(), athlete.getNumber(),
athlete.getName(), athlete.getUnit(), athlete.getScore()));
rank++;
}
reader.close();
writer.close();
}
}
class Athlete implements Comparable<Athlete> {
private String event;
private int lane;
private String number;
private String name;
private String unit;
private double score;
public Athlete(String event, int lane, String number, String name, String unit, double score) {
this.event = event;
this.lane = lane;
this.number = number;
this.name = name;
this.unit = unit;
this.score = score;
}
public String getEvent() {
return event;
}
public int getLane() {
return lane;
}
public String getNumber() {
return number;
}
public String getName() {
return name;
}
public String getUnit() {
return unit;
}
public double getScore() {
return score;
}
@Override
public int compareTo(Athlete o) {
return Double.compare(this.score, o.score);
}
}
```
运行结果会将运动员按照成绩从小到大排名,并将结果按格式保存到输出文件“out.txt”中。
阅读全文