2

I'm trying to average a 2D array column. My code seems to add the number in the row and then divide by the total. In this example there should only be 4 assignments, yet it loops 12 times. Anyone know what's wrong with my code? The numbers are being inputted from a text file, higher up in the full code (not sure if that affects it).

Example Arrays:

[2,3,6,7]
[4,5,6,7]
[2,2,2,2]
System.out.println("Average score of each assignment:");
//TODO: compute and print the average on each assignment
double total = 0;
int totallength = 0;
int assignment = 1;
for (int i = 0; i < myArray.length; i++) {
    for (int j = 0; j < myArray[i].length; j++) {
        total += myArray[i][j];
        totallength++;
        System.out.println("Assignment #" + assignment++
                + " Average: " + (total / totallength));
    }
}

Here is my output:

Average score of each assignment:
Assignment #1 Average: 2.0
Assignment #2 Average: 2.5
Assignment #3 Average: 3.6666666666666665
Assignment #4 Average: 4.5
Assignment #5 Average: 4.4
Assignment #6 Average: 4.5
Assignment #7 Average: 4.714285714285714
Assignment #8 Average: 5.0
Assignment #9 Average: 4.666666666666667
Assignment #10 Average: 4.4
Assignment #11 Average: 4.181818181818182
Assignment #12 Average: 4.0

Desired Output:

Assignment #1 Average: 2.666666666
Assignment #2 Average: 3.333333333
Assignment #3 Average: 4.666666666
Assignment #4 Average: 5.333333333
2
  • 1
    2 for loops, one of 3 elements, the other of 4 - why would you expect it not to run 12 times? Commented Nov 10, 2019 at 22:34
  • @NirLevy sorry. I didn't explain well enough. I added the desired output to show what I'm attempting to do Commented Nov 10, 2019 at 22:38

3 Answers 3

1

You can do it as follows:

public class Main {
    public static void main(String[] args){
        int [][]myArray= {
                {2,3,6,7},
                {4,5,6,7},
                {2,2,2,2},
        };      
        double total=0;
        int assignment=1;

        System.out.println("Average score of each assignment:");
        for(int i=0;i<myArray[0].length;i++) {
            for(int j=0;j<myArray.length;j++) {
                total+=myArray[j][i];          
            }
            System.out.println("Assignment #" + assignment++ + " Average: " + (total/3));
            total=0;
        }
    }
}

Output:

Average score of each assignment:
Assignment #1 Average: 2.6666666666666665
Assignment #2 Average: 3.3333333333333335
Assignment #3 Average: 4.666666666666667
Assignment #4 Average: 5.333333333333333
Sign up to request clarification or add additional context in comments.

2 Comments

The 3x4 2D array is just an example. My numbers in the array is coming from a text file that is read in. Is there a way to find it, given that information?
My apologies! Works great! Thank you.
0

if you want to get the average of each of the rows, you need to initialize your total counters on each oter loop, and also print only on the outer loop after summing:

int assignment=1;
for(int i=0;i<myArray.length;i++) {
    // initialize here, to start each row separatly
    double total=0;
    int totallength=0;
    for(int j=0;j<myArray[i].length;j++) {
        total+=myArray[i][j];
        totallength++;
    }
    // print after the loop, so it will be done only once per row
    System.out.println("Assignment #" + assignment++ + " Average: " + (total/totallength));
}

BTW, much easier way to calculate the averages will be to utilize java 8 stream capabilities:

for(int i=0;i<myArray.length;i++) {
  double average = Arrays.stream(myArray[i]).average().orElse(0d);
} 

2 Comments

Yes, that works for the rows. Is there a way to do it for "columns"?
if you want to make it for columns, you just need to flip the i and j variables in total+=myArray[i][j]; and make the for loops run until the corresponding lengths. keep in mind it will work only in case all rows are of the same size though
0

You can use IntStream.average() method:

int m = 3;
int n = 4;
int[][] arr = {
        {2, 3, 6, 7},
        {4, 5, 6, 7},
        {2, 2, 2, 2}};
double[] averages = IntStream.range(0, n)
        .mapToDouble(i -> IntStream.range(0, m)
                .map(j -> arr[j][i])
                .average()
                .orElse(0))
        .toArray();
// output
IntStream.range(0, averages.length).forEach(i ->
        System.out.println("Assignment #" + (i + 1)
                + " Average: " + (averages[i])));
Assignment #1 Average: 2.6666666666666665
Assignment #2 Average: 3.3333333333333335
Assignment #3 Average: 4.666666666666667
Assignment #4 Average: 5.333333333333333

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.