0

I have an array of objects. I want scan it and as long as the object I find is not null, increase a counter by 1. When I find the first null object, I want to jumb out of the for loop since there is no reason to continue looping.

I wrote the following code:

// counter variable initialized to zero
int counter = 0;

// scan the array
for(int i = 0; i < this.array.length; i++) {

    // as long as the object found is not null
    while(!this.array[i].equals(null)) {

        // increase the value of the counter by 1
        counter += 1;

    }

    // when the first null object found, jump out of the loop
    break;

}

The i++ in the for loop is marked and the warning is Dead Code. However, I guess this makes sense since when I find the first null object, I stop looping. So nothing to worry about, or ...?

PeterHiggs
  • 97
  • 2
  • 10

3 Answers3

5

You're unconditionally breaking out of the for loop at the end of the first iteration of the for loop. That has nothing to do with "when the first null object is found" - it's just at the end of the body of the loop.

Additionally, your while loop is never going to finish unless array[i] really is null (in which case it'll throw a NullPointerException). I think you want:

for (int i = 0; i < this.array.length; i++) {
    if (array[i] != null) {
        counter++;
    } else {
        break;
    }    
}

Or better, use an iterator:

int counter = 0;
for (String item : array) { // Or whatever the type should be
    if (item != null) {
        counter++;
    } else {
        break;
    }
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0

Change the while iteration to if condition as once while condition is true it will not break and go to infinite loop. To match your requirement, use the below code

if(this.array[i] != null) {
    // increase the value of the counter by 1
    counter += 1;
}
else {
    break;
}
Melquiades
  • 8,496
  • 1
  • 31
  • 46
Kick
  • 4,823
  • 3
  • 22
  • 29
0

The most simple solution for this would be:

int counter = 0;
for (Object item : array) {
  if (item == null) {
    break;
  }
  ++counter;
}
Arne Burmeister
  • 20,046
  • 8
  • 53
  • 94