簡體   English   中英

Java for和While循環無法按預期工作

[英]Java for and while loops do no work as expected

這段代碼(Java)不起作用,我不知道為什么。

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; 沒有得到尊重,並再次循環。 我究竟做錯了什么?

您正在呼叫此:

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

其中隱藏了arr [a] [(b + c)],並且c始終等於1。因此,在最后一個for循環開始時,您的b == 2,一切都很好,它進入了循環,並且您正在訪問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!!!

看你的第二個循環

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

你應該這樣

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

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

因此b始終為0。將其更改為:

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

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)))

但這並不意味着那樣。 您仍然可能無法使用陣列。

而且您也忘記了for循環中的++ b增量,就像其他人提到的那樣。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM