In: Computer Science
Language: Java
So I am trying to find the MAJOR and MINOR diagonal SUM and AVERAGE of a 2d matrix using only ONE class. However, the output gives me the incorrect calculations.
This is my class:
public static void MajorAndMinorDiagonalSumAndAvg (Scanner user, int rows, int coluumn, int [][] array) {
double majorarray = 0; double majorarraycount = 0; double minorarray = 0; double minorarraycount = 0;
for (int i = 0; i<array.length; i++)
for(int j =0; j<array[i].length; j++)
{
majorarray += array[i][i];
majorarraycount++;
minorarray += array[i][array.length - i-1];
minorarraycount++;
}
System.out.printf("Major Diagonal Sum: " + "%.2f", majorarray);
System.out.println();
System.out.printf("Major Diagonal Avg: " + "%.2f",majorarray/majorarraycount);
System.out.println();
System.out.printf("Minor Diagonal Sum: " + "%.2f",minorarray);
System.out.println();
System.out.printf("Minor Diagonal Avg: " + "%.2f",minorarray/minorarraycount);
System.out.println();
}
What should I change to get the correct calculations?
public class DiagonalSum {
// method to calculate the MAJOR and MINOR diagonal SUM and AVERAGE of a 2d matrix
// remove user, rows and column parameters from method since they are not used in the function
public static void MajorAndMinorDiagonalSumAndAvg (int [][] array) {
double majorarray = 0, majorarraycount = 0, minorarray = 0, minorarraycount = 0;
// loop over the rows of the input matrix
for(int i=0;i<array.length;i++)
{
majorarray += array[i][i]; // calculate sum of major axis
majorarraycount++; // calculate number of elements in major axis
minorarray += array[i][array.length-i-1]; // calculate sum of minor axis
minorarraycount++; // calculate number of elements in minor axis
}
// output
System.out.printf("Major Diagonal Sum: " + "%.2f", majorarray);
System.out.println();
System.out.printf("Major Diagonal Avg: " + "%.2f",majorarray/majorarraycount);
System.out.println();
System.out.printf("Minor Diagonal Sum: " + "%.2f",minorarray);
System.out.println();
System.out.printf("Minor Diagonal Avg: " + "%.2f",minorarray/minorarraycount);
System.out.println();
}
public static void main(String[] args){
// test the method
int array[][] = {{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5}};
for(int i=0;i<array.length;i++)
{
System.out.println();
for(int j=0;j<array[i].length;j++)
System.out.print(array[i][j]+" ");
}
System.out.println();
MajorAndMinorDiagonalSumAndAvg(array);
}
}
//end of program
Output: