简体   繁体   English

Java中的死代码错误

[英]Dead Code Error in Java

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. 我想对其进行扫描,只要找到的对象不为空,就将计数器加1。当我找到第一个空对象时,由于没有理由继续循环,所以我想跳出for循环。

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. for循环中的i ++被标记,警告为死代码。 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. 在for循环的第一次迭代结束时,您将无条件地脱离for循环。 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 ). 另外,除非array[i]确实为null(在这种情况下,它将引发NullPointerException ),否则while循环永远不会结束。 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;
    }
}

Change the while iteration to if condition as once while condition is true it will not break and go to infinite loop. 将while迭代更改为if条件,而条件为true时它将不会中断并进入无限循环。 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;
}

The most simple solution for this would be: 最简单的解决方案是:

int counter = 0;
for (Object item : array) {
  if (item == null) {
    break;
  }
  ++counter;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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