简体   繁体   中英

Using an if/else statement to return a boolean

I have a method that takes an array as a parameter and returns a boolean.

Inside the method, I have an if/else statement. If the statement is true, I want the result to return true, if the statement is false, I want the statement to returns false.

public static boolean allPositive (double[] arr)
{
    for (int i = 0; i < arr.length; i++)
    {
        if(arr[i] > 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    return //What do i put here?
}

}

Of course, it needs a return value at the end. However, I am confused on what I should return at the bottom. How should I rewrite this?

First, your code is wrong. For example, with {1, -1, 2} , your method will return true.

If you write it differently, you avoid the problem :

public static boolean allPositive (double[] arr) {
  for (int i = 0; i < arr.length; i++) {
    if(arr[i] < 0)
    {
        return false;
    }
  }
  return true;
}

EDIT : Or even better, a one-line solution with Java 8 and Streams (I like one-line solutions):

public static boolean allPositive (double[] arr) {
  //Stream the array and see if any elements matches condition `<0`.
  return !Arrays.stream(arr).anyMatch(i->i<0);
}

If you need more than one line of code in order to work with collections, then you should learn about Streams .

public static boolean allPositive (double[] arr)
{

    boolean b = true;

    for (int i = 0; i < arr.length; i++)
    {
        if(!(arr[i] > 0))
        {
            b = false;
        }

    }
    return b;
}

The way Java works, it ensures no problems with your code by making sure all your returns happen outside of the if else statement. This because, a common bug by programmers is to return in the if else statement, but never create an else condition, so the method never returns anything. Doing it this way is more of a good practice thing so you don't bug out later trying to figure out why a method won't return.

You have to return in the end of the method (after the loop) the value that should be returned if an empty array is passed to your method. It's up to you to decide whether an empty array is "allPositive" or not.

The answer by Arnaud has multiple return statements. Code smell. The answer by DreadHeadedDeveloper has a logic error if the array is {1,-1,2}, it returns true.

This function/method is terse and follows good coding practices.

public static boolean allPositive (double[] arr) {
    boolean ret = true;
    for (int i = 0; i < arr.length; i++) {
        if(arr[i] <= 0) {
            ret = false;
        }
    }
    return ret;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM