2011-07-03 53 views
1

我想計算基於所述價格矩陣中的每一臺之間的票價:如何比較Java中的兩個列表並根據每個組合打印結果?

 a b c 

    a  0 2 3 
    b  4 0 1 
    c  7 2 0 

實施例:from a to b打印2或基於在上述價格矩陣值from c to a打印7

這裏是,我想根據兩個電臺列表打印鐵路票價:「從:」列表和「到:」列表。我想比較後打印票價。每種組合都有固定的票價。例如站a到站b,票價爲10.對於任何一個站到其他站,都有固定的票價。

+3

你能澄清?請舉一個擴展例子。所以如果你有2個字符串bca和acb,你會打印「294」? – user623879

+0

這裏是我想根據列表中的兩個列表列表中的一個「from:」,列出兩個「to:」來打印該列車票價格。我想比較後打印票價。每種組合都有固定的票價。 從車站a到車站b票價爲10. –

+0

從任何一個車站到任何其他車站都有固定票價,它可以是任意組合。 –

回答

1

我會創建一個類,負責存儲票價。

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"); 
+0

非常感謝你!現在我明白了!再次感謝!:) –

+0

不客氣! –

0

你也可以使用guava'sTable

〔實施例:

Table<Integer, String, String> table = HashBasedTable.create(); 
table.put(1, "a", "1a"); 
table.put(1, "b", "1b"); 
table.put(2, "a", "2a"); 
table.put(2, "b", "2b"); 
相關問題