Reputation: 1312
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?
Upvotes: 0
Views: 94
Reputation: 201
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!!!
Upvotes: 1
Reputation: 58
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.
Upvotes: 0
Reputation: 1846
for(int b = 0; b < arr[a].length; /*you're not incrementing b*/)
So b will always be 0. Change it to:
for(int b = 0; b < arr[a].length; b++)
Upvotes: 0
Reputation: 9082
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++
Upvotes: 0