简体   繁体   English

从void和boolean方法返回多个值

[英]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: 我有以下问题:有一个布尔静态方法计算两个整数之间的相似性,我被要求返回4个结果:

  1. without changing the return type of the method, it should stay boolean. 在不改变方法的返回类型的情况下,它应该保持布尔值。
  2. 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): 这是我到目前为止所做的(我无法将返回值从布尔值更改为其他内容,例如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
    }
}

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). 布尔值可以有两个值(true或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? 向函数添加参数是否违反规则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). 通过调用函数4次(使用条件= 1,2,3和4),我们可以检查4个结果(只有一个会返回true,其他3会返回false)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM