Например, я хочу создать функцию, которая может возвращать любое число (отрицательное, нулевое или положительное).
Однако из-за некоторых исключений я бы хотел, чтобы функция возвращала Boolean
FALSE
Есть ли способ написать функцию, которая может возвращать int
или a Логическое
?
Хорошо, так что это получило много откликов. Я понимаю, что просто подхожу к проблеме неправильно, и мне нужно выбросить
какое-то исключение в методе. Чтобы получить лучший ответ, я приведу пример кода. Пожалуйста, не шутите :)
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);
}
}