我會創建一個類,負責存儲票價。
public class FareStorage {
Map<TownCombination, Double> fares;
//...
public double getFare(String townA, String townB) {
return fares.get(new TownCombination(townA, townB));
}
public void addFare(String townA, String townB, double fare) {
fares.put(new TownCombination(townA, townB));
}
class TownCombination {
String town1;
String town2;
//If a fare from A to B is equals the fare from B to A,
//then the A-B and the B-A combinations should be equal.
//Override hashCode and equals the way you want.
}
}
這是不完整的,但我希望你能明白。這是你如何使用它:
FareStorage storage = new FareStorage();
storage.addFare("A", "B", 10.2);
//....
double fare = storage.get("A", "B");
你能澄清?請舉一個擴展例子。所以如果你有2個字符串bca和acb,你會打印「294」? – user623879
這裏是我想根據列表中的兩個列表列表中的一個「from:」,列出兩個「to:」來打印該列車票價格。我想比較後打印票價。每種組合都有固定的票價。 從車站a到車站b票價爲10. –
從任何一個車站到任何其他車站都有固定票價,它可以是任意組合。 –