-2

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.

3
  • Possible duplicate: stackoverflow.com/q/2622725/5743988 Commented Nov 20, 2016 at 21:33
  • Sure this is compiling? Commented Nov 20, 2016 at 21:38
  • I just saw the edit.. I think it is a duplicate of this Commented Nov 20, 2016 at 21:49

3 Answers 3

3

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();
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

-1

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);
}

3 Comments

Fixed code. Now it should work.
You call it by typing averagearray(yourarrayname)
average with a big A

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.