2015-02-08 40 views
2

我不知道我是否在這裏,如果沒有,請隨時刪除此問題。嵌套For-Loop不工作Java

我想遍歷用Java編寫的Minecraft插件中的二維平面塊。所以我想通過每一行的每一個塊。以下是我的代碼。 (顯然縮短)

package mainiterator; 

public class MainIterator { 

    public static void main(String[] args) { 
    int currentX = -2; 
    int currentZ = -2; 
    for (; currentX < 2; currentX++) { 
     for (; currentZ < 2; currentZ++) { 
      //The following should normally be outputted 4*4 Times. (16) 
      System.out.println("currentX:" + currentX + " currentZ:" + currentZ); 
     } 
    } 
    } 
} 

但這僅輸出如下:

currentX:-2 currentZ:-2 
currentX:-2 currentZ:-1 
currentX:-2 currentZ:0 
currentX:-2 currentZ:1 

那麼,有什麼問題? 請隨時嘗試一下。提前致謝!

問候,

來自德國

回答

8

最大的問題是,currentZ是在錯誤的地方進行初始化。它應該在內環之前被初始化:

int currentX = -2; 
for (; currentX < 2; currentX++) { 
    int currentZ = -2; 
    for (; currentZ < 2; currentZ++) { 
     //The following should normally be outputted 4*4 Times. (16) 
     System.out.println("currentX:" + currentX + " currentZ:" + currentZ); 
    } 
} 

如果您使用的,因爲他們的意思是使用循環您本來可以避免這樣的錯誤:

for (int currentX = -2; currentX < 2; currentX++) { 
    for (int currentZ = -2; currentZ < 2; currentZ++) { 
     //The following should normally be outputted 4*4 Times. (16) 
     System.out.println("currentX:" + currentX + " currentZ:" + currentZ); 
    } 
} 
+0

哦,是的,非常感謝!我習慣於在for(;;)語句中使用初始值設定項來執行C++循環,但是我不太熟悉Java中變量的變量初始化,因此我只是把它們放在外面。 – 2015-02-08 13:30:00