E. Hazard E. Hazard - 19 days ago 6
Java Question

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

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.

Answer

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