How to write Java function that returns values of multiple data types?

后端 未结 11 1562
耶瑟儿~
耶瑟儿~ 2021-01-03 23:34

For example, I want to create a function that can return any number (negative, zero, or positive).

However, based on certain exceptions, I\'d like the function to re

11条回答
  •  孤城傲影
    2021-01-04 00:02

    Absolutely! In your case, since the return values can be positive, 0, negative, or false, probably the best return value would be a JSONObject. In your code, you would add this import:

    import org.json.JSONObject;
    

    and in the function:

    JSONObject retval = new JSONObject();
    double x = b*b - 4*a*c;
    if(x < 0){
        retval.put("result", false);
    }
    else{
        retval.put("result", x);
    }
    

    You potentially could also add another key:value pair to the retval to include the result type to help with checking it in the calling function.

提交回复
热议问题