Summing Up A 2D Array

。_饼干妹妹 提交于 2019-12-04 07:05:57

问题


Given my current program, I would like it to calculate the sum of each column and each row once the user has entered all their values. My current code seems to be just doubling the value of the array. This is not what I'm looking to do. For example, if the user enters a 3x3 matrix with the following values 1 2 3 2 3 4 3 4 5 it will look like I have it formatted in my program below. (see comment at top)

Then I also want to modify the code so it picks out the diagonal and prints that out so that output would read: Main Diagonal: {1,3,5}


回答1:


Your code is ok, but at the end for summation of column you should change the rows instead of column. like this:

System.out.println("\n");

    for( int column = 0; column < columns; column++)
    {
        for(int row = 0; row < rows; row++)
            {
            array2d[row][column] = array2d[row][column] + array2d[row][column];
            System.out.print(array2d[row][column] + " ");
            }
         System.out.println();
    }



回答2:


Welcome to the world of Java. First of let's dissect your "doubling the array" code.

array2d[row][column] = array2d[row][column] + array2d[row][column];

This line of code is the issue. The loops that you have applied tend to update the values of each of the elements in the matrix. For e.g. Suppose

array2d[1][2]=2

Hence the code mentioned above does this

array2d[1][2]= array2d[1][2]+array2d[1][2];

which essentially doubles the value of the array.

You should try something like this:

//To print the values of rows

    for(int i=0;i<rows;i++)
    {
        int rowValue=0;

        for(int j=0;j<columns;j++)
        {

            //Print current row value
            rowValue = rowValue + array2d[i][j];

        }
        System.out.println("ROW" +i+ "=" + rowValue);

    }

The below code will help you calculate the value of columns.

   //To print values of columns
    for(int i=0;i<columns;i++)
    {
        int columnValue=0;

        for(int j=0;j<rows;j++)
        {

            //Print current row value
            columnValue = columnValue + array2d[i][j];

        }
        System.out.println("COLUMN" +i+ "=" + columnValue);

    }

Try making the code for the diagonal.It's pretty straightforward.

HINT : Main diagonals have row and column number to be the same.

P.S. - Add scan.close() to your code. Always close such connections to prevent resource leaks.




回答3:


For main diagonal

for(int i=0;i<columns;i++)
    {
    for(int j=0;j<rows;j++)
    {
         if(i==j){
          System.out.println(a[i][j]+ "\n"); 
          }
        }

    }


来源:https://stackoverflow.com/questions/21820588/summing-up-a-2d-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!