Why does this code have a missing return statement error?

前端 未结 6 969
情话喂你
情话喂你 2020-12-21 00:50

If I change the else if portion of this code to an else statement it runs without any problems so I get how to make it run. What I\'m a little confused about is why I get a

6条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-21 00:56

    You should have a return in all your branches.

    public boolean posNeg(int a, int b, boolean negative) {
      if (!negative) {
        return (a < 0 && b > 0) || (a > 0 && b < 0);
      }
      else if (negative) {
        return (a < 0 && b < 0);
      }
    }
    

    The method above logically has a return in all branches, but technically it does not. We like the Java compiler to be fast, therefore it is undesirable to have a Java compiler analyzing semantically the code.

    public boolean posNeg(int a, int b, boolean negative) {
      if (!negative) {
        return (a < 0 && b > 0) || (a > 0 && b < 0);
      }
      else {
        return (a < 0 && b < 0);
      }
    }
    

    The method above has a return in all the branches.

    public boolean posNeg(int a, int b, boolean negative) {
      if (!negative) {
        return (a < 0 && b > 0) || (a > 0 && b < 0);
      }
      return (a < 0 && b < 0);
    }
    

    However, as you can see above, you do not even need the else, because if the code ever reaches the second return, then negative is certainly false, as if it was true, the first return would end the algorithm.

    public boolean posNeg(int a, int b, boolean negative) {
      return ((negative) && (a < 0 && b < 0)) || ((!negative)  && (a < 0 && b > 0) || (a > 0 && b < 0));
    }
    

    The method above is a one-liner.

    public boolean posNeg(int a, int b, boolean negative) {
      return ((negative) && (a < 0 && b < 0)) || ((!negative)  && ((a < 0) == (b > 0)));
    }
    

    The method above uses the fact that in the second case the positivity of a is equal with the negativity of b.

提交回复
热议问题