2009-10-04 66 views
0

在此方法的前兩個FOR循環之後,我遇到了讀/ println問題。 這很奇怪。我怎麼解決這個問題?在循環中打印時出現問題:對於

private int spacing() { 
    int n = numberOfTriangles(); 

    ArrayList<Double> list_Xs1 = new ArrayList<Double>(); 
    ArrayList<Double> list_Ys1 = new ArrayList<Double>(); 

    for(Polygon p:triangles){ 
     double cX = p.xpoints[0]; 
     double cY = p.ypoints[2]; 
     list_Ys1.add(cY); 
     list_Xs1.add(cX); 
    } 

    //Remove duplicate key in X 
    HashSet<Double> hashSet_list_Xs1= new HashSet<Double>(list_Xs1); 
    ArrayList<Double> list_Xs2 = new ArrayList<Double>(hashSet_list_Xs1); 
    Collections.sort(list_Xs2); 

    //Remove duplicate key in Y 
    HashSet<Double> hashSet_list_Ys1= new HashSet<Double>(list_Ys1); 
    ArrayList<Double> list_Ys2 = new ArrayList<Double>(hashSet_list_Ys1); 
    Collections.sort(list_Ys2); 

    ArrayList<Double> list_Xs3 = new ArrayList<Double>(); 
    ArrayList<Double> list_Ys3 = new ArrayList<Double>(); 
    double distanceX = 0.0,distanceY=0.0; 

    //Get Distance between X coordinate 
    for (int j=0; j<list_Xs2.size(); j++){ 
     distanceX = Math.abs(list_Xs2.get(j) - list_Xs2.get(j+1)); 
     list_Xs3.add(distanceX); 
     System.out.println("I am able to print everything inside this loop"); 
    } 

    System.out.println("After the LOOP for (int j=0; j<list_Xs2.size(); j++), the method seems stop reading the remaining line e.g. cannot print after this loop "); 

    //Get Distance between Y coordinate  
    for (int i=0; i<list_Ys2.size(); i++){ 
     distanceY = Math.abs(list_Ys2.get(i) - list_Ys2.get(i+1)); 
     list_Ys3.add(distanceY); 
     System.out.println("Nothing printed in this loop"); 
    } 

    //Remove duplicate key in Y 
    HashSet<Double> hashSet_list_Ys2= new HashSet<Double>(list_Ys3); 
    ArrayList<Double> list_Ys4  = new ArrayList<Double>(hashSet_list_Ys2) ; 

    //Remove duplicate key in X 
    HashSet<Double> hashSet_list_Xs2 = new HashSet<Double>(list_Xs3); 
    ArrayList<Double> list_Xs4 = new ArrayList<Double>(hashSet_list_Xs2) ; 

    int distinctDistance_Xs = list_Xs4.size(); 
    int distinctDistance_Ys = list_Ys4.size(); 


    int nSpacing = distinctDistance_Xs + distinctDistance_Ys; 

    int RMspacing=0; 
    if (n==1) 
     RMspacing = 1; 
    else if (n != 1) 
     RMspacing = 1 - ((nSpacing-1)/(2*(n-1))); 

    return RMspacing; 
} 
+2

您的環境不包含調試器嗎?你用什麼開發? – 2009-10-04 11:41:22

回答

0

感謝大家提出的所有建議,我忘記了最後一次迭代的次數,與最後一次迭代次數相同。我通過加-1來解決問題。

for (int j=0; j<list_Xs2.size()-1; j++){ 
    .... 
} 


for (int j=0; j<list_Ys2.size()-1; j++){ 
    .... 
} 
1

拋出的任何異常?

如果不是,則打印出list_Ys2.size()的值,它很可能是零。

1
for (int j=0; j<list_Xs2.size(); j++){ 
    distanceX = Math.abs(list_Xs2.get(j) - list_Xs2.get(j+1)); 
    ... 
} 

這會拋出一個IndexOutOfBoundsException異常最後一次迭代,當j+1等於size()

1

你的代碼運行到在list_Xs2循環的IndexOutOfBoundsException;顯然你的執行環境忽略了stderr,這是一個壞主意。此外,我建議花時間學習使用調試器,這使得調查這種問題非常快速和容易。