“缺少退货声明”在if / for / while中 [英] "Missing return statement" within if / for / while
问题描述
我有一个关于中使用的返回语句的问题if()
while()
或 for()
语句。
正如您在以下方法中看到的那样,期望我返回
一个字符串值。
问题是,如果我在 if
语句块中使用 return
语句,编译器将返回错误缺少返回语句
。
I have a question regarding return statements used within if()
while()
or for()
statements.
As you can see in the following method, it is expecting that I return
a String value.
The problem is that if I were to use a return
statement within my if
statement block, the compiler would return the error missing return statement
.
public String myMethod()
{
if(condition)
{
return x;
}
}
当然我可以将方法标题更改为 void
并使用 System.out.println
而不是 return
。但这是正确的方法吗?我错过了什么吗?
Of course I could change the method header to void
and use System.out.println
instead of return
. But is this the right way to do it? am i missing something?
非常感谢任何帮助。
推荐答案
如果你在中放置return语句,如果
,,而
或为
声明然后它可能会或可能不会返回值。如果它不会进入这些语句,那么该方法也应返回一些值(可能为null)。为了确保这一点,编译器将强制您编写此返回语句,该语句在之后
,,而
或 for
。
If you put return statement in if
, while
or for
statement then it may or may not return value. If it will not go inside these statement then also that method should return some value ( that could be null). To ensure that, compiler will force you to write this return statement which is after if
, while
or for
.
但如果你写如果
/ else
阻止它们中的每一个都在其中返回然后编译器知道如果
或 else
将获得执行,方法将返回一个值。所以这次编译器不会强迫你。
But if you write if
/ else
block and each one of them is having return in it then compiler knows that either if
or else
will get execute and method will return a value. So this time compiler will not force you.
if(condition)
{
return;
}
else
{
return;
}
这篇关于“缺少退货声明”在if / for / while中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!