How to find average of elements in 2d array JAVA?

2020-05-10 09:08发布

问题:

I need help with the following program:

"Write a method that will take a two-dimensional array of doubles as an input parameter & return the average of the elements of the array."

Can anyone tell me how to go about it?

My current code:

public static double average(float arr[][]) {
double sum = 0;
int count = 0;
for (int row = 0; row < arr.length; row++)
for (int col = 0; col < arr[0].length; col++) 
{
sum += arr[row][col];
count++;
}
return sum/count;
}

I don't know how to let the user input the array elements and array dimensions (row/columns). Also how do I call this method from main? I am getting errors.

回答1:

try this:

Code:

public class AverageElements {
    private static double[][] array;

    public static void main (String[] args){

        //  Initialize array
        initializeArray();

        //  Calculate average
        System.out.println(getAverage());
    }   

    private static void initializeArray(){
        array = new double[5][2];
        array[0][0]=1.1;
        array[0][1]=12.3;
        array[1][0]=3.4;
        array[1][1]=5.8;
        array[2][0]=9.8;
        array[2][1]=5.7;
        array[3][0]=4.6;
        array[3][1]=7.45698;
        array[4][0]=1.22;
        array[4][1]=3.1478;
    }

    private static double getAverage(){
        int counter=0;
        double sum = 0;
        for(int i=0;i<array.length;i++){
            for(int j=0;j<array[i].length;j++){
                sum = sum+array[i][j];
                counter++;
            }
        }

        return sum / counter;
    }
}

Output:

5.452478000000001


回答2:

If you want to to all in one line (two-dimensional int array):

Arrays.stream(array).flatMapToInt(Arrays::stream).average().getAsDouble();

If you deal with a two-dimensional double array:

Arrays.stream(array).flatMapToDouble(Arrays::stream).average().getAsDouble();


回答3:

Since you asked so nicely! Here is the code:

public double Averagearray(double[][] array) {
    double total=0;
    int totallength;
    for(int i=0;i<array.length;i++) {
        for(int j=0;j<array[i].length;j++) {
            total+=array[i][j];
            totallength++;
        }
    }
    return total/(totallength);
}