2013-12-12 63 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

相关问题