I’m studying Java. And i wanted to make the code for checking a 2D array that returns if it is a magic square or not.
In order to do that, i had to write couple of different methods and one of them was for checking is all the sum of elements in each columns are equal. I could do for rows, but i got little bit confused vwhen i tried to do that for columns. And my friend said it’s almost same with the method which check all row’s sums are equal. My method for rows are below.
public static boolean rowSumsOK(int arr[][], int total) {
boolean a = false;
total = sumOneRow(arr);
int x=0; // this will be counted sum for each rows
for (int i=0; i<arr.length; i++){
for (int j=0; j<=arr.length; j++){
x = x + arr[i][j];
}
if(x != total){
a = false;
break;
}
else
a = true;
}
return a;
}
and he suggested to change in that method for doing it for columns is:
x = x + arr[j][i];
I’m still little bit confused about this. Can you explain me for this method or show me another way to do it guys?
1 Answer