【问题标题】:Why do I get an error for not having a return statement even though I have one in my for loop?为什么即使我的 for 循环中有一个 return 语句,我也会因为没有 return 语句而收到错误消息?
【发布时间】: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语句。

标签: java return


【解决方案1】:

尚不清楚 size 是在哪里定义的,但假设 index &lt; size 永远不会为真,那么您的 return 语句就永远不会出现

因此,方法作用域需要所有可能的代码路径的最终返回语句

【讨论】:

    【解决方案2】:

    因为在编译时编译器不知道变量的值。因此编译器无法评估条件并检查条件是真还是假。因此消除了给出错误的“return -1”语句。希望这能消除您的困惑。

    【讨论】:

      猜你喜欢
      • 2013-12-22
      • 2011-08-26
      • 2017-05-22
      • 1970-01-01
      • 2023-03-26
      • 2017-02-24
      • 2011-08-17
      • 2014-08-28
      相关资源
      最近更新 更多