quot;Missing return statementquot; within if / for / while(“缺少退货声明在 if/for/while 内)
问题描述
我对 if()
while()
或 for()
语句中使用的 return 语句有疑问.
I have a question regarding return statements used within if()
while()
or for()
statements.
正如您在下面的方法中看到的,它期望我 return
一个字符串值.问题是,如果我在 if
语句块中使用 return
语句,编译器将返回错误 missing return statement
.
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?
推荐答案
如果在 if
、while
或 for
语句,那么它可能会也可能不会返回一个值.如果它不会进入这些语句,那么该方法也应该返回一些值(可能为 null).为确保这一点,编译器将强制您在 if
、while
或 for
之后编写此返回语句.
If you put a return statement in the if
, while
or for
statement then it may or may not return a value. If it will not go inside these statements 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
.
但是,如果您编写了一个 if
/else
块并且每个块中都有一个返回,那么编译器就会知道 if
或 else
将被执行并且该方法将返回一个值.所以这次编译器不会强迫你.
But if you write an if
/ else
block and each one of them is having a return in it then the compiler knows that either the if
or else
will get executed and the method will return a value. So this time the compiler will not force you.
if(condition)
{
return;
}
else
{
return;
}
这篇关于“缺少退货声明"在 if/for/while 内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:“缺少退货声明"在 if/for/while 内
基础教程推荐
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 降序排序:Java Map 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01