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
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();
}
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");
}
}
}
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.