1. Member
Join Date
Feb 2012
Location
Posts
10
Rep Power
0

## MagicSquare.java Printing

I've created an application to create a Magic Square, and I have the formulas correct, but I can't quite get the formatting right when I print it out.

Here's the code:

Java Code:
```import java.util.Scanner;

public class MagicSquare{
public static void main (String args[]){

Scanner input = new Scanner(System.in);
int N;

while (true)
{
System.out.println("Please input the size of the Magic Square:");
N = input.nextInt();
if (N%2==1&&N<=21)
{
break;
}
}
int [][]magic = new int[N][N];
int row = N -1;
int col = N/2;
magic[row][col] = 1;

for (int i = 2; i <= N*N; i++){
if (magic[(row + 1) % N][(col + 1) % N] == 0){
row = (row + 1) % N;
col = (col + 1) % N;
}
else
{
row = (row - 1 + N) % N;
}
magic [row][col] = i;
}
System.out.println("-----------------");
for(int i = 0; i < N; i++){
System.out.println("----------------------");
for(int j = 0; j < N; j++)
{
if (magic[i][j] < 10)
System.out.print(" | ");
if (magic[i][j] < 100) System.out.print(" ");
System.out.printf("%4d",magic[i][j]);
}
}
}
}```
...and here's how it looks when I print it out with 3 integers down and 3 across:
-----------------
----------------------
| 4 | 9 | 2----------------------
| 3 | 5 | 7----------------------
| 8 | 1 | 6

...and here's how I'd like it to look:
-----------
4 | 9 | 2 |
-----------
3 | 5 | 7 |
-----------
8 | 1 | 6 |
-----------

Can someone please let me know what I need to do to make it look like that? I appreciate your help!
Last edited by Norm; 03-23-2012 at 07:36 PM.

2. ## Re: MagicSquare.java Printing

It looks like you want to print the line of ---- on the next line. Move the printing to a new line by calling println or by printing "\n"

3. Member
Join Date
Feb 2012
Location
Posts
10
Rep Power
0

## Re: MagicSquare.java Printing

Thanks very much, that worked perfectly. One last thing, if I choose to make the Magic Square larger it screws up the formatting and I've been pulling my hair out trying to figure out why. Any ideas? Here's what it looks like when I print it...

----------------------
11 18 25 | 2 | 9
----------------------
10 12 19 21 | 3
----------------------
| 4 | 6 13 20 22
----------------------
23 | 5 | 7 14 16
----------------------
17 24 | 1 | 8 15
----------------------

4. ## Re: MagicSquare.java Printing

There are classes with methods for formatting numbers that will add padding spaces.
See the DecimalFormat class and the String class's format method.