【发布时间】:2011-06-24 13:59:33
【问题描述】:
例如,我想创建一个可以返回任何数字(负数、零或正数)的函数。
但是,基于某些例外情况,我希望函数返回 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);
}
}
【问题讨论】:
-
你已经得到了很多答案,所以你可以看到它是可能的,但不是很好。我建议你解释一下你需要它做什么。然后你很可能会得到一个更好的解决方案。顺便说一句,异常也可以通过抛出异常来表示。返回 Boolean.FALSE 并且从不返回 Boolean.TRUE 是代码异味,请考虑返回 Integer 并返回 null 而不是 FALSE。
-
使用返回值是C风格的编程。并不是说这有什么问题,而是考虑例外情况。这就是它们的目的。
标签: java methods overloading