0

我有一个对象数组。我想扫描它,只要我找到的对象不为空,就将计数器加 1。当我找到第一个空对象时,我想跳出 for 循环,因为没有理由继续循环。

我写了以下代码:

// 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;

}

for循环中的i++被标记,警告为Dead Code。但是,我想这是有道理的,因为当我找到第一个空对象时,我会停止循环。所以没什么好担心的,或者......?

4

3 回答 3

5

在循环的第一次迭代结束时,您将无条件地for退出 for循环。这与“找到第一个空对象时”无关——它只是在循环体的末尾。

此外,除非真的为 null (在这种情况下它会抛出一个) ,否则您的while循环永远不会完成。我想你想要:array[i]NullPointerException

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

或者更好的是,使用迭代器:

int counter = 0;
for (String item : array) { // Or whatever the type should be
    if (item != null) {
        counter++;
    } else {
        break;
    }
}
于 2014-02-25T18:15:56.820 回答
0

将 while 迭代更改为if条件,因为当条件为真时,它不会中断并进入无限循环。要满足您的要求,请使用以下代码

if(this.array[i] != null) {
    // increase the value of the counter by 1
    counter += 1;
}
else {
    break;
}
于 2014-02-25T18:18:55.290 回答
0

最简单的解决方案是:

int counter = 0;
for (Object item : array) {
  if (item == null) {
    break;
  }
  ++counter;
}
于 2014-02-25T18:21:30.357 回答