Magic square class (modular math problem)

• June 29th, 2010, 10:37 PM
mjpam
Magic square class (modular math problem)
Hi, I'm new to Java. I am trying to write a program that will print magic squares of odd order.

Here is the code:

Code :

```class MagicSquare { public static void main (String args[]) { if(args.length > 1) { System.out.println("Too many arguments entered"); } else { int sqrOrd = Integer.parseInt(args[0]); int magSqr[][] = new int [sqrOrd][sqrOrd]; if (sqrOrd % 2 == 0) { System.out.println("Square order is even"); } else { int rowNum; int colNum;   for (rowNum = 0; rowNum < sqrOrd; rowNum++) { for (colNum = 0; colNum < sqrOrd; colNum++) { magSqr[rowNum][colNum] = -1; //System.out.print(magSqr[rowNum][colNum]); } System.out.println(); }   int maxNum = sqrOrd * sqrOrd; rowNum = 0; colNum = sqrOrd / 2 + 1; magSqr[rowNum][colNum] = 1;   for (int curNum = 1; curNum <= maxNum; curNum++) { if (magSqr[(rowNum - 1 + sqrOrd) % sqrOrd][(colNum + 1) % sqrOrd] == -1) { rowNum = (rowNum - 1 + sqrOrd) % sqrOrd; colNum = (colNum - 1 + sqrOrd) % sqrOrd; } else { rowNum = (rowNum + 1) % sqrOrd; } magSqr[rowNum][colNum] = curNum; } for (rowNum = 0; rowNum < sqrOrd; rowNum++) { for (colNum = 0; colNum < sqrOrd; colNum++) { System.out.print(magSqr[rowNum][colNum] + " "); } System.out.println(); } } } } }```

My main problem is that, while the code compiles without any errors or warnings, the program does not print a magic square; it print an array where only some of the elements are replaced by the numbers 1 through n^2.

I think I am having some problem with the math controlling the if statements. Any help would be appreciated.
• June 30th, 2010, 10:56 AM
Norm
Re: Magic square class (modular math problem)