possibleRoutes
是HashSet<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]
僅供參考,出現了一個'Math.hypot'功能(請參閱http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#hypot(double,double))來計算像sqrt(x * x + y * y)這樣的東西。 – ajb
move'ArrayList routesDistances = new ArrayList ();'for for loop –
@IlyaBursov之外,問題是他打印的方式不應該打印'[xxxx] [xxxx]':除非'routesDistances'的大小爲' 1'。含糊不清的問題。 – Sage