Comment écrire une fonction Java qui renvoie des valeurs de plusieurs types de données?

Par exemple, je veux créer une fonction qui permet de retourner un nombre quelconque (négatif, nul ou positif).

Cependant, en fonction de certaines exceptions, j'aimerais que la fonction de retour Boolean FALSE

Est-il un moyen d'écrire une fonction qui renvoie un int ou un Boolean?


Ok, donc cela a reçu beaucoup de réponses. Je comprends que je suis tout simplement en approchant le problème de manière incorrecte et je dois throw quelque sorte d'Exception dans la méthode. Pour obtenir une meilleure réponse, je vais donner un exemple de code. Merci de ne pas faire plaisir 🙂

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);

  }

}

source d'informationauteur maček