如何编写返回多种数据类型值的Java函数? [英] How to write Java function that returns values of multiple data types?
问题描述
例如,我想创建一个可以返回任何数字(负数,零或正数)的函数。
For example, I want to create a function that can return any number (negative, zero, or positive).
但是,基于某些例外,我' d喜欢返回的函数 Boolean
FALSE
However, based on certain exceptions, I'd like the function to return Boolean
FALSE
是有一种方法可以编写一个函数,可以返回 int
或一个布尔
?
Is there a way to write a function that can return an int
or a Boolean
?
好的,所以收到了很多回复。我知道我只是错误地解决了这个问题,我应该抛出
方法中的某种异常。为了得到更好的答案,我将提供一些示例代码。请不要取笑:)
Ok, so this has received a lot of responses. I understand I'm simply approaching the problem incorrectly and I should throw
some sort of Exception in the method. To get a better answer, I'm going to provide some example code. Please don't make fun :)
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做到这一点。
No, you can't do that in Java.
你可以返回对象
虽然。通过返回一个对象,你可以在技术上返回一个派生类,如 java.lang.Integer
或 java.lang.Boolean
。但是,我认为这不是最好的主意。
You could return an Object
though. And by returning an object you could technically return a derived class such as java.lang.Integer
or java.lang.Boolean
. However, I don't think it's the best idea.
这篇关于如何编写返回多种数据类型值的Java函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!