Saad - 7 months ago 57

Java Question

So i am trying to sum the diagonals and compare it to a magic constant number. If they are the same, then it is a magic square. I was able to write the code for the diagonals however it is showing me incorrect result. My code is here:

`public static boolean checkDiagonals(int[][] array, int magicConstant){`

int total = 0;

int wrong = 0;

for(int i = 0; i < array.length; i++){

total= total + array[i][i] + array[array.length - i-1][array.length - i-1];

}

if(total!=magicConstant){

wrong++;

}

System.out.println("There were " + wrong + " invalid diagnals.");

return wrong == 0;

}

Size: 3

1 1 1

5 5 5

9 9 9

1 1 1

5 5 5

9 9 9

The magic constant is 15

There were 1 invalid diagnals.

This is NOT a magic square.

Size: 3

8 1 6

3 5 7

4 9 2

8 1 6

3 5 7

4 9 2

The magic constant is 15

There were 1 invalid diagnals.

This is NOT a magic square.

Why i believe there is something wrong with my code is that i am getting

`There were 1 invalid diagnals.`

I have a problem getting the correct output. I believe it has got something to do with addition of digonals Why is it that it keeps printing 1 invalid diagonal for every square. The output that i have shown is just for 2 squares however when i try it with other squares, it keeps printing

`1 invalid diagonal`

Answer

See discussion in comments for more details:

```
public static boolean checkDiagonals(int[][] array, int magicConstant){
int total1 = 0;
int total2 = 0;
int wrong = 0;
for(int i = 0; i < array.length; i++){
total1= total1 + array[i][i];
total2 = total2 + array[array.length - i-1][array.length - i-1];
}
if(total1!=magicConstant){
wrong++;
}
if(total2!=magicConstant){
wrong++;
}
System.out.println("There were " + wrong + " invalid diagnals.");
return wrong == 0;
}
```

Source (Stackoverflow)