“Missing return statement” within if / for / while

后端 未结 7 973
粉色の甜心
粉色の甜心 2020-11-22 02:02

I have a question regarding return statements used within if() while() or for() statements. As you can see in the following method, it

7条回答
  •  说谎
    说谎 (楼主)
    2020-11-22 02:05

    That's because the function needs to return a value. Imagine what happens if you execute myMethod() and it doesn't go into if(condition) what would your function returns? The compiler needs to know what to return in every possible execution of your function

    Checking Java documentation:

    Definition: If a method declaration has a return type then there must be a return statement at the end of the method. If the return statement is not there the missing return statement error is thrown.

    This error is also thrown if the method does not have a return type and has not been declared using void (i.e., it was mistakenly omitted).

    You can do to solve your problem:

    public String myMethod()
    {
        String result = null;
        if(condition)
        {
           result = x;
        }
        return result;
    }
    

提交回复
热议问题