简体   繁体   中英

Java for and while loops do no work as expected

This piece of code (Java) does not work, and I can't figure out why.

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++;
      }
   }
}

Problem: b < arr[a].length; does not get respected and loops again. What am I doing wrong?

You're calling this:

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

There's arr[a][(b + c)] hidden in it, and c is always equals 1. So your b == 2 at the time the last for-loop starts, all is well, it enters the loop, and the you're accessing b+c element (2+1), but there's only 3 elements in the inner array, maximum index shouldn't be greater than 2!

There's your bug. First loop:

  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++;
  }

Second loop:

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

Look at your second for loop

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

you should do it like this

for(int b = 0; b < arr[a].length; b++) { - You forgot the 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 gets out of array

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

I think you wanted to do that in the condition of while loop such that

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

But this doesn't mean that. You can still be out of array.

And also you forgot the ++b increment in for loop like mentioned by others.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM