my task is to write a program that ask user for an input and the method will return whether or not the input forms a magic square. No matter what I enter into the console, the p
isMagicSquare()
.isMagicSquare()
is wrong in many points.
x > side
should be x < side
.sumD
only after is calculation is finished.sumX
and sumY
before calculating them.+=
instead of =+
to calculate the sum.To correct:
Make the code save the input
do{
System.out.print("Enter an int. Enter -1 when done>");
current = Integer.parseInt(in.nextLine());
if (current != -1) ints.add(current); // add this line to the loop to read the input
}while(current != -1);
and correct isMagicSquare()
.
private static Boolean isMagicSquare(int[][] array){
int side = array.length;
int magicNum = 0;
for(int x = 0; x < side; ++x){
magicNum += array[0][x];
}
int sumD = 0;
for(int x = 0; x < side; ++x){
int sumX = 0;
int sumY = 0;
for (int y = 0; y < side; ++y){
sumX += array[x][y];
sumY += array[y][x];
}
sumD =+ array[x][x];
if(sumX != magicNum || sumY != magicNum){
return false;
}
}
return sumD == magicNum;
}