2013-12-12 58 views
1

possibleRoutesHashSet<ArrayList<Integer>>的類型。 possibleRoutes中的每個數組列表都包含按行駛順序彼此連接的管道或火車站的ID。打印一個數組列表,並選擇一個索引?

for(ArrayList<Integer> route : possibleRoutes) { 

     ArrayList<Double> routesDistances = new ArrayList<Double>(); // list of the total distances of the routes 

     double distance = 0; 

     for (int i=1; i < route.size()-1; i++){ 
      double x = Math.abs(stationLocations.get(route.get(i)).getX() - stationLocations.get(route.get(i-1)).getX()); 
      double y = Math.abs(stationLocations.get(route.get(i)).getY() - stationLocations.get(route.get(i-1)).getY()); 
      double d = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)); 

      distance += d;; 
     } 

     routesDistances.add(distance); 

     System.out.print(routesDistances); 

    } 

這是輸出至今:

[2163.9082950470897][3494.746239392733][2099.5269818921306][2075.3141294013] 

我想打印出來的列表作爲一個數組列表,在那裏我可以從列表中選擇,如routesDistances.get(0)作爲第一索引的索引。你怎麼做,這樣的列表將是一個類型的ArrayList<Double>和返回爲:

[2163.9082950470897, 3494.746239392733, 2099.5269818921306, 2075.3141294013] 
+0

僅供參考,出現了一個'Math.hypot'功能(請參閱http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#hypot(double,double))來計算像sqrt(x * x + y * y)這樣的東西。 – ajb

+1

move'ArrayList routesDistances = new ArrayList ();'for for loop –

+0

@IlyaBursov之外,問題是他打印的方式不應該打印'[xxxx] [xxxx]':除非'routesDistances'的大小爲' 1'。含糊不清的問題。 – Sage

回答

0

要打印出來的列表作爲一個數組列表,在那裏我可以從列表中選擇,如 指數routesDistances.get(0)至於第一個 索引。

由於@IlyaBursov建議,您可以在for循環之前聲明routesDistances

而且,從具體指標進行打印,您可以使用subList(fstIndex, lstIndex)功能如下:

System.out.print(routesDistances.subList(index, aList.size())); 
1

只要把

ArrayList<Double> routesDistances = new ArrayList<Double>(); 

for(ArrayList<Integer> route : possibleRoutes) 

之前之後循環您routesDistances將是這樣的:[2163.9082950470897,3494.746239392733,2099.5269818921306,2075.3141294013]

,然後在一個循環的輸出只寫這樣的:

for(Double d:routesDistances){ 
    System.out.println(d); 
} 
+0

問題解決了!謝謝 – user3079679

相關問題