例如,我想創建一個可以返回任意數字(負數,零或正數)的函數。如何編寫返回多個數據類型值的Java函數?
然而,根據某些例外情況,我想函數返回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,返回空值而不是FALSE。 – maaartinus 2011-02-10 03:04:19
使用返回值是C風格的編程。並不是說這有什麼不妥,而是考慮例外。這是他們的目標。 – duffymo 2011-02-10 03:05:20