简体   繁体   English

Java:if/else 语句可以与“返回真”和“返回假”一起使用吗

[英]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.

相关问题 如果输入在数组中,则返回true,否则返回false - If an input is in the array return true, else false 如果值为假,则使用流返回 null 否则返回真 - Using streams return null if value is false else return true 在处理中将true语句返回false - Return a true statement back to false in Processing Java中的文件名以.java结尾。 给定文件名,如果它是一个java文件,则返回true,否则返回false - A file name in java ends in .java. Given the name of the file, return true if its a java file, else return false ((Java)if / else if / else循环后的返回语句? - ((Java) Return statement after if/else if/else loop? Java:取2个数组查找是否存在于两个数组中的元素如果存在则返回true否则为false - Java : Taking 2 array find if the element that exists in both array return true if exist else false 如果您可以将一个列表拆分为一个更小的列表,并且在已分区列表中至少包含两个值,则返回 true,否则返回 false - Returning true if you can split a list into smaller list with minimum two values in the parted list else return false Java搜索LinkedList的数据返回true / false? - Java Searching LinkedList for data return true/false? Java - 装箱整数 - 为什么如果返回false则返回true - Java - boxing integer - why it return true if should return false 它返回false而不是true - It return false instead of true
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM