例如,我想创建一个可以返回任何数字(负数、零或正数)的函数。
但是,基于某些例外情况,我希望函数返回 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);
}
}
原文由 maček 发布,翻译遵循 CC BY-SA 4.0 许可协议
不,你不能在 Java 中这样做。
不过,您可以返回
Object
。通过返回一个对象,您可以在技术上返回一个派生类,例如java.lang.Integer
或java.lang.Boolean
。但是,我认为这不是最好的主意。