Return multiple values from void and boolean methods

I have the following problem: Having a boolean static method that computes similarity between two integers, I am asked to return 4 results:

  • without changing the return type of the method, it should stay boolean.
  • without updating/using the values of external variables and objects
  • This is what I've done so far (I can't change return value from boolean to something else, such as an int, I must only use boolean):

    public static boolean isSimilar(int a, int b) {
        int abs=Math.abs(a-b);
        if (abs==0) {
        return true;
        } else if (abs>10) {
        return false;
        } else if (abs<=5){
            //MUST return something else, ie. semi-true
        } else {
            //MUST return something else, ie. semi-false
        }
    }
    

    The following is bad practice anyway, but If you can try-catch exceptions you can actually define some extra outputs by convention. For instance:

    public static boolean isSimilar(int a, int b) {
        int abs = Math.abs(a-b);
        if (abs == 0) {
            return true;
        } else if (abs > 10) {
            return false;
        } else if (abs <= 5){
            int c = a/0; //ArithmeticException: / by zero (your semi-true)
            return true; 
        } else {
            Integer d = null;
            d.intValue(); //NullPointer Exception (your semi-false)
            return false;
        }
    }
    

    A boolean can have two values (true or false). Period. So if you can't change the return type or any variables outside (which would be bad practice anyway), it's not possible to do what you want.


    Does adding a parameter to the function violate rule 2? If not, this might be a possible solution:

    public static boolean isSimilar(int a, int b, int condition) {
        int abs = Math.abs(a - b);
        switch (condition) {
        case 1:
            if (abs == 0) {
                return true; // true
            }
        case 2:
            if (abs > 10) {
                return true; // false
            }
        case 3:
            if (abs <= 5 && abs != 0) {
                return true; // semi-true
            }
        case 4:
            if (abs > 5 && abs <= 10) {
                return true; // semi-false
            }
        default:
            return false;
        }
    }
    

    By calling the function 4 times (using condition = 1, 2, 3 and 4), we can check for the 4 results (only one would return true, other 3 would return false).

    链接地址: http://www.djcxy.com/p/86646.html

    上一篇: 为什么C ++不支持堆栈上的动态数组?

    下一篇: 从void和boolean方法返回多个值