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 ...?
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;
}
}
See more on this question at Stackoverflow