public class TestMagicSquare { public static void main (String [] args) { int [][] a = {{6,7,2}, {1,5,9}, {8,3,4}}; System.out.println (isMagicSquare (a) ); } public static boolean isMagicSquare (int [][] a) { int i,j; int total = 0; int length = a.length; int testTotal = 0; int value; //use the following array to keep track of which numbers you //have encountered in your matrix boolean [] used = new boolean [length * length +1]; used[0] = true; //cycle through the matrix and check to see if the value has been //encountered previously for (i = 0; i < length; i++) { for (j = 0; j < length; j++) { value = a[i][j]; if ((value >= used.length) || (value < 1)) return false; if (used[value]) //already saw the value - there is a repeat return false; else used[value] = true; // mark the value as seen } } //first diagonal - set the total that each total should be equal to for (i = 0; i < length; i++) total += a[i][i]; System.out.println(total); //second diagonal for (i = 0; i < length; i++) testTotal += a[i][length-i-1]; System.out.println(testTotal); if (total != testTotal) return false; //check rows for (i = 0; i < length; i++) { testTotal = 0; for (j = 0; j < length; j++) testTotal += a[i][j]; System.out.println(testTotal); if (total != testTotal) return false; } //check columns for (i = 0; i < length; i++) { testTotal = 0; for (j = 0; j < length; j++) testTotal += a[j][i]; System.out.println(testTotal); if (total != testTotal) return false; } return true; } }