I am pretty new at programming and need some feedback as to why this program is not working??? It was a pretty big undertaking for me but I can't seem to figure out what is wrong:
Code:
import java.util.*;
public class MagicSquare
{
public static void isMagic (int[][] b)
{
int sum = 0;
System.out.print('\n' + "Sum of Columns: ");
for (int i =0 ; i < b.length; i++)
{
for (int j= 0; j< b[i].length; j++)
{
sum= sum+b[0][j];
}
System.out.print(sum + " ");
sum = 0;
}
System.out.println(" ");
System.out.print("Sum of Rows: ");
int x =0;
while (x < b.length)
{
for (int i =0 ; i < b.length; i++)
{
sum= sum + b[i][x];
}
System.out.print(sum + " ");
sum=0;
x++;
}
{
System.out.println(" ");
System.out.print("Sum of Diagonals: ");
for (int i =0 ; i < b.length; i++)
{
for (int j= 0; j< b[i].length; j++)
{
sum= sum+b[0][j];
}
System.out.print(sum + " ");
sum = 0;
i++;
}
}
}
// returns true if sq is a magic square
boolean isMagicTest(int [][] b, int[][] xArray)
{
int sum = 0;// the sum that all rows, columns, and diags should equal
for (int i = 0; i < b.length; i++)
{
sum += b[i][0];
}
int diag1 = 0;
int diag2 = 0; // the sums of the two diagonals
for (int i = 0; i < b.length; i++)
{
int hor = 0, vert = 0; // the sums of the current row and column
for (int j = 0; j < b[i].length; j++)
{
if (b[i][j] == 0) return false;
hor += b[i][j];
vert += b[j][i];
}
if (hor != sum || vert != sum)
return false;
diag1 += b[i][i];
diag2 += b[2-i][i];
}
if (diag1 != sum || diag2 != sum)
//return false;
System.out.println("This is not a Magic square!");
return false;
// no failures found, so we have a magic square!
//return true;
System.out.println("This is a Magic square!");
return true;
}
public static void main (String[] args)
{
int[][] xArray = {{5, 9, 1}, {3, 4, 8}, {7, 2, 6}};
int[][] yArray = {{1, 3, 16, 14}, {8, 15, 2, 9},
{13, 6, 11, 4}, {12, 10, 5, 7}};
int[][] zArray = {{18, 24, 5, 6, 12}, {10, 11, 17, 23, 4},
{22, 3, 9, 15, 16}, {14, 20, 21, 2, 8},
{1, 7, 13, 19, 25}};
isMagic(xArray);
//isMagic(yArray);
//isMagic(zArray);
}
}
Comment