Java中的死代码错误
我有一个对象数组。我想扫描它,只要我找到的对象不是空的,就增加一个计数器1。当我找到第一个空对象时,我想退出for循环,因为没有理由继续循环 我编写了以下代码:Java中的死代码错误,java,dead-code,Java,Dead Code,我有一个对象数组。我想扫描它,只要我找到的对象不是空的,就增加一个计数器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 nu
// 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;
}
//计数器变量初始化为零
int计数器=0;
//扫描阵列
for(int i=0;i
for循环中的i++被标记,警告是死代码。然而,我想这是有意义的,因为当我找到第一个空对象时,我停止循环。所以没什么好担心的,或者…?在for
循环的第一次迭代结束时,您将无条件地跳出for循环。这与“找到第一个空对象时”无关——它只是在循环体的末尾
此外,除非数组[i]
真的为空(在这种情况下,它将抛出NullPointerException
),否则while
循环永远不会结束。我想你想要:
for (int i = 0; i < this.array.length; i++) {
if (array[i] != null) {
counter++;
} else {
break;
}
}
在for
循环的第一次迭代结束时,您将无条件地跳出for循环。这与“找到第一个空对象时”无关——它只是在循环体的末尾
此外,除非数组[i]
真的为空(在这种情况下,它将抛出NullPointerException
),否则while
循环永远不会结束。我想你想要:
for (int i = 0; i < this.array.length; i++) {
if (array[i] != null) {
counter++;
} else {
break;
}
}
将while迭代更改为
如果
条件为一次,而条件为true,则不会中断并进入无限循环。要符合您的要求,请使用以下代码
if(this.array[i] != null) {
// increase the value of the counter by 1
counter += 1;
}
else {
break;
}
将while迭代更改为
如果
条件为一次,而条件为true,则不会中断并进入无限循环。要符合您的要求,请使用以下代码
if(this.array[i] != null) {
// increase the value of the counter by 1
counter += 1;
}
else {
break;
}
最简单的解决方案是:
int counter = 0;
for (Object item : array) {
if (item == null) {
break;
}
++counter;
}
最简单的解决方案是:
int counter = 0;
for (Object item : array) {
if (item == null) {
break;
}
++counter;
}
在一次迭代后,您正在打破循环。因此,您永远不会转到increment语句。您的while循环不应该是循环。。。它应该是一个if语句,在一次迭代后,您正在中断循环。因此,您永远不会转到increment语句。您的while循环不应该是循环。。。它应该是一个if语句oops!我想用if语句代替while,这总是让我困惑!谢谢哎呀!我想用if语句代替while,这总是让我困惑!谢谢