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
Your outer loop in isMagicSquare
is never entered, so you always return true.
Change
for(int x = 0; x > side; ++x)
to
for(int x = 0; x < side; ++x)
Beside that, sumD != magicNum
should only be tested outside the outer loop, otherwise your method will return false in cases that should return true. And sumX
and sumY
should be reset in each iteration of the outer loop.
Therefore isMagicSquare()
should look like this :
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;
}
In addition, you forgot to add the inputs to ints
:
do{
System.out.print("Enter an int. Enter -1 when done>");
current = Integer.parseInt(in.nextLine());
if (current != -1) ints.add(current); // add this
}while(current != -1);
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;
}