某舉重比賽排名規則:
需從資料檔案讀取選手資訊(編號、總重量、體重),依規則排序後輸出編號。本文示範如何透過實作 Comparable<T> 介面完成自定義排序邏輯。
<p> <no>1</no> <lw>140</lw> <bw>54</bw> </p>
<p> <no>2</no> <lw>155</lw> <bw>53</bw> </p>
<p> <no>3</no> <lw>140</lw> <bw>42</bw> </p>
<p> <no>4</no> <lw>140</lw> <bw>55</bw> </p>
<p> <no>5</no> <lw>130</lw> <bw>46</bw> </p>
class Athlete implements Comparable<Athlete> {
private int id;
private int totalWeight; // 總舉起重量
private int bodyWeight; // 體重
public Athlete(int id, int totalWeight, int bodyWeight) {
this.id = id;
this.totalWeight = totalWeight;
this.bodyWeight = bodyWeight;
}
@Override
public int compareTo(Athlete other) {
// 規則1:總重量降序(大者在前)
if (this.totalWeight != other.totalWeight) {
return Integer.compare(other.totalWeight, this.totalWeight);
}
// 規則2:體重升序(輕者在前)
return Integer.compare(this.bodyWeight, other.bodyWeight);
}
// Getter 方法
public int getId() { return id; }
public int getTotalWeight() { return totalWeight; }
public int getBodyWeight() { return bodyWeight; }
}
public class WeightliftingRanking {
public static void main(String[] args) {
List<Athlete> athletes = new ArrayList<>();
String filePath = "data4.txt"; // 檔案路徑
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
String line;
// 簡易解析:假設每 5 行一組資料,第 2、3、4 行分別為 no、lw、bw
// 實務建議使用 XML/JSON 解析器
while ((line = br.readLine()) != null) {
if (line.contains("<no>")) {
int id = extractValue(line, "no");
int totalWeight = extractValue(br.readLine(), "lw");
int bodyWeight = extractValue(br.readLine(), "bw");
athletes.add(new Athlete(id, totalWeight, bodyWeight));
br.readLine(); // 讀掉 </p>
}
}
} catch (IOException e) {
e.printStackTrace();
}
// 排序
athletes.sort(null); // 使用 Comparable 自然順序
// 輸出結果
for (Athlete a : athletes) {
System.out.printf("%d. 總重量:%d 體重:%d%n", a.getId(), a.getTotalWeight(), a.getBodyWeight());
}
}
// 簡易標籤值提取輔助方法
private static int extractValue(String line, String tag) {
String pattern = "<" + tag + ">(\\d+)</" + tag + ">";
return Integer.parseInt(line.replaceAll(".*" + pattern + ".*", "$1"));
}
}
依規則排序後順序為:
compareTo 回傳負數表示 this 排在前,正數表示 other 排在前,零視為相等。Integer.compare() 避免減法溢位風險,程式碼更清晰。Comparator 策略模式,將排序邏輯外部化。