Returning null in a function that should return an integer

Felka98 :

The code identifies the integer that is closest to 0 in an array and if there are 2 or more values that meet this condition the return value should be null.The problem is that when I make the condition to return null it displays an error because the function is supposed to return an integer.

    static int function(int [] arr){
    int closest=arr[0];
    for(int i=1;i<arr.length;i++){
        if(Math.abs(arr[i])<closest){
            arr[i]=closest;
        }
        else if(arr[i]==closest){
            return null;
        }
    }
    return closest;
}

I am very new to Java (learned Python before),if there is a better/more eficient approach to this code please share.

GBlodgett :

You can convert the return type to Integer which can hold null and will auto box and unbox to an int:

static Integer function(int [] arr){
    int closest=arr[0];
    for(int i=1;i<arr.length;i++){
        if(Math.abs(arr[i])<closest){
            arr[i]=closest;
        }
        else if(arr[i]==closest){
            return null;
        }
    }
    return closest;
}

However this is probably not the best solution. You could instead return Integer.MAX_VALUE to signify that two of the elements were equidistant from zero. This depends on how you plan to handle the case where there are two elements of equal distance to 0.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=86827&siteId=1