我正在尝试编写一个方法来查看特定颜色的对象数组,这也是一个对象。
public Ghost findFirst(Color c){
for (int i=0;i<ghosts.length;i++) {
if (ghosts[i].getColor()==c)
return ghosts[i];
else
return null;
}
}
因此,如果某个幽灵的颜色与颜色c匹配,则返回该幽灵。但是,我收到了i ++的死代码警告。我的代码有什么问题?哦,我也得到一个方法错误,说这个函数应该返回一个鬼。我以为我是?
答案 0 :(得分:7)
因为你在第一次迭代时从循环返回!所以“我”永远不会增加。完全删除else块或将“return null”更改为“continue”。
作为一个单独的点,==正在检查引用相等,而不是对象相等。您似乎应该使用“.equals”代替
答案 1 :(得分:3)
固定代码:
public Ghost findFirst(Color c){
for (int i=0;i<ghosts.length;i++) {
if (ghosts[i].getColor().equals(c))
return ghosts[i];
}
return null;
}
请记住return
终止函数(显然包括循环)。因此,如果您找到了正确的颜色幽灵 - 您将其返回(从而结束搜索并且永远不会到达return null;
行)。如果你的for循环没有找到 - 你到达最后一行并返回null。
答案 2 :(得分:2)
因为
else
return null;
<!/ P>
由于return-Statement,你的循环只会被执行一次。
答案 3 :(得分:2)
public Ghost findFirst(Color c){
for (int i=0; i < ghosts.length; i++) {
if (ghosts[i].getColor().equals(c))
return ghosts[i];
}
return null;
}
答案 4 :(得分:1)
如果我'展开'你的循环,代码就像:
public Ghost findFirst(Color c){
if (ghosts[0].getColor()==c)
return ghosts[0];
else
return null;
if (ghosts[1].getColor()==c)
return ghosts[1];
else
return null;
if (ghosts[2].getColor()==c)
return ghosts[2];
else
return null;
//etc...
}
应该清楚,它永远不会达到第二个if
,它会在第一个if
返回(突破函数),真或假。
答案 5 :(得分:0)
您的多个return
可能有问题。有时它会使一个return
更简单。
public Ghost findFirst(Color c) {
Color color = null;
for (int i=0;i<ghosts.length;i++) {
if (ghosts[i].getColor().equals(c))
color = ghosts[i];
}
return color;
}