methods - How to write Java function that returns values of multiple data types? -
for example, want create function can return number (negative, zero, or positive).
however, based on exceptions, i'd function return boolean false
is there way write function can return int or boolean?
ok, has received lot of responses. understand i'm approaching problem incorrectly , should throw sort of exception in method. better answer, i'm going provide 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 exception here. how handle 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! understand code can adjusted accommodate imaginary numbers, sake of example, let's have function throw exception , coefficients invalid */ } return (-b + math.sqrt(x) * polarity) / (2*a); } }
no, can't in java.
you return object though. , returning object technically return derived class such java.lang.integer or java.lang.boolean. however, don't think it's best idea.
Comments
Post a Comment