Return 来自 void 和 boolean 方法的多个值

Return multiple values from void and boolean methods

我遇到以下问题:有一个计算两个整数之间相似度的布尔静态方法,我被要求 return 4 个结果:

  1. 在不改变方法的 return 类型的情况下,它 应该保持布尔值。
  2. 没有updating/using外部变量和对象的值

这是我目前所做的(我无法将 return 值从布尔值更改为其他值,例如 int,我必须只使用布尔值):

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
    }
}

布尔值可以有两个值(真或假)。时期。因此,如果您不能更改 return 类型或外部的任何变量(无论如何这都是不好的做法),则无法执行您想要的操作。

以下无论如何都是不好的做法,但如果您可以尝试捕获异常,您实际上可以按照约定定义一些额外的输出。例如:

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

向函数添加参数是否违反规则 2?如果没有,这可能是一个可能的解决方案:

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

通过调用该函数 4 次(使用条件 = 1、2、3 和 4),我们可以检查 4 个结果(只有一个 return 为真,其他 3 个 return假)。