Home > Net >  I am working on an exercise to create an 2D java array that displays every number as a table and has
I am working on an exercise to create an 2D java array that displays every number as a table and has

Time:01-27

So i have to make this program and I was able to make the program display the array with the row averages but I am finding it difficult to also display the column averages. My problems are that: 1. I cannot figure out how to add the column value similar to how I did with the row values. 2. I am also having trouble displaying the average column values below the table. Can anybody help?

public class ColRowAvg
{
   public static void main (String args[])
   {
      int avg = 0;
      int[][] arr = {{6,3,4,2}, {3,4,5,7}, {3,6,7,2}, {3, 5, 2, 7}};
      for (int row = 0; row < arr.length; row  )//Cycles through rows
      {
         for (int col = 0; col < arr[row].length; col  )//Cycles through columns
         {
            System.out.printf("]", arr[row][col]);
            avg  = arr[row][col];
         }
         System.out.printf(" |-", avg/arr.length);
         System.out.println(); //Makes a new row
         avg = 0;
      }
      System.out.println();
      for (int col = 0; col < arr.length; col  )//Cycles through rows
      {
         for (int row = 0; row < arr[col].length; row  )//Cycles through columns
         {
            System.out.printf("]", arr[row][col]);
            avg  = arr[row][col];
         }
         System.out.printf(" |-", avg/arr.length);
         System.out.println(); //Makes a new row
         avg = 0;
      }      
   }
}

This is what I have right now.

CodePudding user response:

Just swap row and col in nested for loop

  •  Tags:  
  • Related