首页 文章

从void和boolean方法返回多个值

提问于
浏览
3

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

  • 如果不改变方法的返回类型,它应该保持布尔值 .

  • 没有更新/使用外部变量和对象的值

这是我到目前为止所做的(我无法将返回值从布尔值更改为其他内容,例如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
    }
}

3 回答

  • 2

    以下是不好的做法,但如果您可以尝试捕获异常,您可以按惯例实际定义一些额外的输出 . 例如:

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

    布尔值可以有两个值(true或false) . 期 . 因此,如果您无法更改返回类型或外部的任何变量(无论如何这都是不好的做法),那么就无法做您想做的事情 .

  • 1

    向函数添加参数是否违反规则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个结果(只有一个会返回true,其他3会返回false) .

相关问题