我有一个关于在语句if() while()或for()语句中使用的返回语句的问题.正如您在下面的方法中所看到的,它期望我return是一个String值.问题是,如果我return在if语句块中使用语句,编译器将返回错误missing return statement.
public String myMethod()
{
if(condition)
{
return x;
}
}
Run Code Online (Sandbox Code Playgroud)
当然,我可以将方法标题更改为void并使用System.out.println而不是return.但这是正确的方法吗?我错过了什么吗?
任何帮助都非常感谢.
如果你把返回语句if,while或for语句那么它可能会或可能不会返回值.如果它不会进入这些语句,那么该方法也应返回一些值(可能为null).为了确保,编译器会强迫你写这个return语句是后if,while或for.
但是,如果你写if/ else块,并将它们中的每一个具有它的回报则编译器知道,要么if或else将得到执行和方法会返回一个值.所以这次编译器不会强迫你.
if(condition)
{
return;
}
else
{
return;
}
Run Code Online (Sandbox Code Playgroud)
那是因为函数需要返回一个值。想象一下,如果执行myMethod()但未进入if(condition)函数返回的结果,会发生什么?编译器需要知道在函数的每次可能执行中返回什么
检查Java文档:
定义:如果方法声明具有返回类型,则方法末尾必须有一个return语句。如果return语句不存在,则会抛出缺少的return语句错误。
如果该方法没有返回类型并且未使用void声明(即错误地省略了该方法),则也会引发此错误。
您可以解决您的问题:
public String myMethod()
{
String result = null;
if(condition)
{
result = x;
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
那是非法语法。返回变量不是一个可选的事情。您必须返回您在方法中指定类型的变量。
public String myMethod()
{
if(condition)
{
return x;
}
}
Run Code Online (Sandbox Code Playgroud)
你实际上是在说:我保证任何类都可以使用这个方法(公共),并且我保证它将始终返回一个字符串(String)。
那么你是说如果我的条件为真我将返回x。嗯,那太糟糕了。你的承诺里没有任何“如果”。您承诺 myMethod 将始终返回一个字符串。
即使您的条件始终为真,编译器也必须假设它有可能为假。因此,您始终需要在任何条件之外的非 void 方法的末尾添加一个 return,以防所有条件都失败。
public String myMethod()
{
if(condition)
{
return x;
}
return ""; // Or whatever the default behavior will be if all of your conditions fail to return.
}
Run Code Online (Sandbox Code Playgroud)