Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning null in a function that should return an integer

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.

like image 387
Felka98 Avatar asked Feb 01 '26 23:02

Felka98


1 Answers

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.

like image 142
GBlodgett Avatar answered Feb 03 '26 11:02

GBlodgett