2014-01-19 77 views
0

這段代碼(Java)不起作用,我找不出原因。Java for while while循環無法按預期工作

int[][] arr = {{0, 0, 0}, {0, 1, 0}, {0, 0, 0}}; 

for(int a = 0; a < arr.length; a++) { 
    for(int b = 0; b < arr[a].length;) { 
     int c = 1; 
     if (arr[a][b] == 0) { 
     while((arr[a][(b+c)] == 0) && ((b+c)!=(arr[a].length-1))) { 
      c++; 
     } 
     addBar(b, a, c); // Use these values in another function... 
     b = b + c; 
     } else { 
     b++; 
     } 
    } 
} 

問題:b < arr[a].length;沒有得到尊重和再次循環。我究竟做錯了什麼?

+0

而在循環 – Pierre

+1

循環使用調試,看看會發生什麼。 –

回答

0

看看你的第二個for循環

for(int b = 0; b < arr[a].length;) {

你應該做這樣的

for(int b = 0; b < arr[a].length; b++) { - 你忘了在B ++

+1

我正在手動增加b臨近for循環的末尾,因爲可能需要通過'c'增加,這就是'if()'的用處。 – Laurent

0
for(int b = 0; b < arr[a].length; /*you're not incrementing b*/) 

所以B將始終爲0變更它可以:

for(int b = 0; b < arr[a].length; b++) 
+1

我在for循環結束時手動增加b,因爲可能需要通過'c'增加,這就是'if()'的用處。 – Laurent

0

B + C失控陣列

if(b+c<arr[a].length) 
     { 
      while((arr[a][(b+c)] == 0) && ((b+c)!=(arr[a].length-1))) 
      {   
       c++; 
     } 
     } 

的我想你想做的事,在while循環,使得

((b+c)!=(arr[a].length-1))) 

但是,這並不意味着狀態。你仍然可能不在陣列中。

而且你忘記了++循環中的++ b增量,就像其他人提到的一樣。

1

你調用此:

while ((arr[a][(b + c)] == 0) && ((b + c) != (arr[a].length - 1))) 

有ARR [A] [(B + C)隱藏在它和c總是等於1 所以你的b == 2的時候最後一個for循環開始,一切都很好,它進入循環,並且你正在訪問b + c元素(2 + 1),但內部數組中只有3個元素,最大索引不應大於2!

有你的錯誤。第一環:

int c = 1;//b==0 
    if (arr[a][b] == 0) {//arr[0][0] - correct 
    while((arr[a][(b+c)] == 0) && ((b+c)!=(arr[a].length-1))) { 
     c++; //c == 2 
    } 
    addBar(b, a, c); // Use these values in another function... 
    b = b + c; //b == 0 + 2 == 2 
    } else { 
    b++; 
    } 

第二環:

int c = 1;//b== 2 
    if (arr[a][b] == 0) {//arr[0][2] - correct 
    while((arr[a][(b+c)] == 0) //ERROR!!! b+c == 3!!!