尝试查找数组总和时 Eclipse 中的死代码
我尝试使用 for 循环查找任何数组的总和,但 i++ 部分最终成为无法访问的死代码。我不明白为什么?
public static int sum(int[] data) {
int sum = 0;
int i;
for (i = 0; i < data.length; i++) { //the i ++ is the deadcode
sum += data [i];
return sum;
}
return 0;
}
I tried to find the sum of any array by using the for loop but the i++ part ended up being the deadcode unreachable. I don't understand why?
public static int sum(int[] data) {
int sum = 0;
int i;
for (i = 0; i < data.length; i++) { //the i ++ is the deadcode
sum += data [i];
return sum;
}
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
i++
是死代码,因为它永远无法访问。它永远无法到达,因为循环中有一个 return 语句。因此,它永远不会执行 for 循环的增量部分。将return sum;
移到循环之外(替换return 0;
)。The
i++
is dead code because it can never be reached. It can never be reached because you have a return statement within the loop. Therefore, it will never execute the increment portion of the for-loop. Move thereturn sum;
outside the loop (replacing thereturn 0;
).不要在 for 循环中返回任何内容,因为 return 结束了整个函数的循环。
相反,做这样的事情:
Don't return something inside for loop, because return ends the cycle of whole function.
Instead, do something like this:
您总是在第一次迭代后返回,因此除了第一个元素之外,您不会对任何内容求和。
你应该这样做:
}
You are always returning after the first iteration so you do not sum anything besides the first element.
You should do it like this :
}