我想在给定数组中找到平均值,并在 java 中找到最接近该平均值的数字

I want to find the average in a given array, and find the closest number to that average in java

我想计算最接近数组平均值的数,我已经计算完平均值但我不知道如何找到最接近该平均值的数。

public class ClosestToTheArray {
int array [] = new int[]{1, 2, 3 ,4 ,5, 6 ,7 ,8};
int sum;
int sum2;

public void findAverage(){
    double avg;
    double lol = 0;
    double smthelse;
    for(int i =0; i < array.length; i++){
        sum += array[i];
    }
    avg = sum/array.length;
}

public static void main(String [] args){
    ClosestToTheArray test = new ClosestToTheArray();
    test.findAverage();
}

}

求给定数组的平均值,并找出最接近平均值的数,

public static void main(String[] args)
{
    int array[] = new int[]
    { 1, 2, 3, 4, 5, 6, 7, 8 };
    int sum=0;

    double avg;
    for (int i = 0; i < array.length; i++)
    {
        sum += array[i];
    }
    avg = sum / array.length;
    System.out.println(avg);
    
    double difference = Math.abs(array[1] - avg);
    Integer closest = array[1];
    for (int i = 0; i < array.length; i++)
    {
        double diff = Math.abs(array[i] - avg);
        if(difference > diff)
        {
            difference = diff;
            closest = array[i];
        }
    }
    System.out.println(closest);
}