例如,我想创建一个可以返回任何数字(负数,零或正数)的函数。

但是,基于某些异常(exception),我希望该函数返回Boolean FALSE
有没有一种方法可以编写可以返回int Boolean的函数?

好的,因此收到了很多答复。我知道我只是错误地解决了这个问题,我应该在方法中throw某种异常。为了获得更好的答案,我将提供一些示例代码。请别取笑:)

public class Quad {

  public static void main (String[] args) {

    double a, b, c;

    a=1; b=-7; c=12;
    System.out.println("x = " + quadratic(a, b, c, 1));   // x = 4.0
    System.out.println("x = " + quadratic(a, b, c, -1));  // x = 3.0


    // "invalid" coefficients. Let's throw an exception here. How do we handle the exception?
    a=4; b=4; c=16;
    System.out.println("x = " + quadratic(a, b, c, 1));   // x = NaN
    System.out.println("x = " + quadratic(a, b, c, -1));  // x = NaN

  }

  public static double quadratic(double a, double b, double c, int polarity) {

    double x = b*b - 4*a*c;

    // When x < 0, Math.sqrt(x) retruns NaN
    if (x < 0) {
      /*
        throw exception!
        I understand this code can be adjusted to accommodate
        imaginary numbers, but for the sake of this example,
        let's just have this function throw an exception and
        say the coefficients are invalid
      */
    }

    return (-b + Math.sqrt(x) * polarity) / (2*a);

  }

}

最佳答案

不,您无法在Java中做到这一点。

您可以返回Object。通过返回对象,从技术上讲,您可以返回派生类,例如java.lang.Integerjava.lang.Boolean。但是,我认为这不是最好的主意。

07-24 09:38
查看更多