[英]Java: Can the if/else statement be used with a 'return true' and a 'return false'
public boolean ifElseStatement(){
if(conditions){
statementBody++;
return true;
}
else
return false;
If the condition is met, will this method return true
?如果满足条件,这个方法会返回
true
吗? Or might it return false
because it the final return
statement is outside of the if
body?或者它可能返回
false
因为它最终的return
语句在if
主体之外?
I am effectively asking is this correct use of the if/else statement when a boolean value needs to be returned?我实际上是在问,当需要返回布尔值时,是否正确使用 if/else 语句? Or perhaps there is a better or universally preferred way to do this?
或者也许有更好或普遍首选的方法来做到这一点?
To clarify, I am asking if the if-else statement can be used like this, with two return statements.为了澄清,我在问 if-else 语句是否可以像这样使用,带有两个 return 语句。 I have always been told to use only one return statement.
我一直被告知只能使用一个 return 语句。
If the condition is true, it will not be able to hit the return of the else
statement.如果条件为真,它将无法命中
else
语句的返回。 Once it hits a return, your code immediately returns to where the ifElseStatement()
was invoked.一旦遇到返回,您的代码会立即返回到调用
ifElseStatement()
位置。 Returning a Value from a Method 从方法返回值
The method will return the first return statement reached.该方法将返回到达的第一个 return 语句。 If conditions == true, will return true, in other case, will return false.
如果conditions == true,则返回true,否则返回false。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.