【发布时间】:2020-03-08 08:08:50
【问题描述】:
我正在编写一个方法,它是大学作业的 Queue 类的一部分。它应该在链表中搜索对象,如果找到则返回对象的索引,如果不是则返回-1。当我没有“return -1;”时在下面的代码中声明我收到一条错误消息,指出当我在 for 循环中显然有一个以上语句时,我没有返回语句。这里有什么问题?
public int find(Object item) {
Node current = head;
for(int index = 0; index < size; index++) {
if(current.data.equals(item)) {
return index;
}
else {
current = current.next;
}
}
return -1;
}
【问题讨论】:
-
问题是你的方法需要指定如果另一个 return 语句从不执行,它应该返回什么。否则,如果您指定的项目在您的链表中没有找到,该方法的返回值是什么?
-
你可以删除
else。 -
因为循环可以结束而不执行里面的return语句。