Search code examples
javamatrixmagic-square

Sum of individual rows and columns in user-specified matrix in Java


This assignment involves a 'matrix.txt' file that is to be imported into the program. This file can have a matrix of any size. The prof has furnished a working program to properly import this file, and has set the task of the students to determine if this file is a Magic Square. I know this means getting the sum of each row and each column and then comparing the values to see if they are equal. My problem is that I do not know how to specify a single rows' value that does not have to be immediately printed out, thereby losing the value when the loop repeats. I would like a way that will store each value so they can be checked for equality after the loop has iterated over all the possible rows and columns. since I have no idea what the size of the array will be, I cannot 'hard code' values, and would have to use stuff like:

sum = 0;
for (i = 0; i < matrix.length; i++)
{
for (j = 0; j < matrix[i].length; j++)

I am looking for a way to individualize the values of each row and column so I can compare them later. Then I would print out "The matrix is a magic square", or "The matrix is not a magic square"


Solution

  • Would some code like this work?

    boolean isMagicSquard = true;
    int sum = -1;
    for (int i = 0; i < matrix.length; i++){
        // Calculate the sum for each row
        int rowsum = 0;
        for (int j = 0; j < matrix[i].length; j++){
            rowsum += matrix[j][i];
        }
        if (sum == -1){ 
            sum = rowsum; 
        }else if (sum != rowsum){ // If the sum differs from the 
                                  // first-row sum, it is no magic squaree
            isMagicSquard = false; break; 
        }
    }
    // The same code with rows and column swaped
    for (int i = 0; i < matrix[0].length; i++){
        int columnsum = 0;
        for (int j = 0; j < matrix.length; j++){
            columnsum += matrix[i][j];
        }
        if (sum != columnsum ){ 
            isMagicSquard = false; break; 
        }
    }
    System.out.println(isMagicSquare);