【问题标题】:Why does eclipse say I have no return statement in this method [closed]为什么eclipse说我在这个方法中没有return语句[关闭]
【发布时间】:2015-08-26 02:45:15
【问题描述】:

我用 Eclipse IDE 为我在 java 中做的一个类编写了一个辅助方法。该方法的代码如下

private foo getfooMonitor(String id)
{
    if(fooList.isEmpty())
    {
        if (Mgr.getValue(Name, ListPath + id) == null)
        {
            return null;
        }
    }
    else
    {
        for(foo f : fooList)
        {
            if(f.getID().equalsIgnoreCase(id))
            {
                return foo;
            }
        }
        return null;
    }
}

我很好奇为什么该方法会被强制返回一些东西,因为它有一个 if then else 块,无论如何都有一个 return 语句命中,为什么 eclipse 会认为我没有返回语句?

这个 Eclipse 是否强制执行一些奇怪的语法,因为它无法解析 if then else 块以查看该方法将被强制返回,或者这是一个 java 的东西,不允许 non void 方法有效,除非它有return 语句作为方法体中的最后一行?

【问题讨论】:

  • 如果Mgr.getValue 不是null,你会返回什么?
  • @SotiriosDelimano 是一个辅助函数,因此如果调用代码的返回值为 null,则需要处理代码。
  • 您认为哪个更有可能:Eclipse 错了,还是您的代码错了?
  • 如果Mgr.getValue 不是nullgetfooMonitor 方法会返回什么?
  • @SotiriosDelimanolis 啊,明白了。当你指出时才注意到。不是想问一个愚蠢的问题,或者如果有什么我不知道的事情真的很好奇。

标签: java eclipse methods syntax ide


【解决方案1】:

并非所有路径都返回。如果Mgr.getValue(Name, ListPath + id) == null 返回 false 则您的方法没有返回值

【讨论】:

    【解决方案2】:

    不是每个执行路径都有一个返回值:如果fooList.isEmpty(),但Mgr.getValue(Name, ListPath + id) != null 怎么办?永远不会输入内部if。外部else 被忽略,因为外部if 已输入。因此,程序到达一个状态,方法结束,但没有返回任何内容。

    旁注:关于执行路径,Java 编译器非常愚蠢。以下面的方法为例:

    boolean isTrue(boolean value) {
        if (value) {
            return (true);
        }
        if (!value) {
            return (false);
        }
    }
    

    通过tertium non datur,执行第一个或第二个if。但是这段代码仍然给出了相同的编译错误。让它运行的唯一方法是将if (!value) 更改为else(语义上是相同的)。

    【讨论】:

      【解决方案3】:

      您在原始 if 语句中的嵌套 if 语句中只有一个 return 语句。如果Mgr.getValue(Name, ListPath + id) != null但外部语句有效,则没有return语句。

      【讨论】:

        【解决方案4】:
        private foo getfooMonitor(String id)
        {
            if(fooList.isEmpty())
            {
                if (Mgr.getValue(Name, ListPath + id) == null)
                {
                    return null;
                } else {
                    //this path does not return a value 
                }
            }
            else
            {
                for(foo f : fooList)
                {
                    if(f.getID().equalsIgnoreCase(id))
                    {
                        return foo;
                    }
                }
                return null;
            }
        }
        

        查看注释中没有返回的路径。

        【讨论】:

          猜你喜欢
          • 2021-02-12
          • 1970-01-01
          • 1970-01-01
          • 2016-01-24
          • 2012-10-04
          • 2014-12-18
          • 2021-05-06
          • 2017-03-17
          • 2017-05-22
          相关资源
          最近更新 更多