如何编写返回多种数据类型值的Java函数? [英] How to write Java function that returns values of multiple data types?

查看:106
本文介绍了如何编写返回多种数据类型值的Java函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我想创建一个可以返回任何数字(负数,零或正数)的函数。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆