import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class MagicSquare {
public static void main(String[] args) {
int n = 0;
System.out.println("请输入幻方的阶数:");
try {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
n = Integer.parseInt(in.readLine());
}
catch (IOException e) {
System.out.println("输入环节发生错误!");
}
int[][] matrix = new int[n][n];
if (n % 4 == 1 || n % 4 == 3) {
//阶数是奇数
getMagicSquare13(matrix, n);
}
//阶数不是奇数的情况……
//显示幻方
printMagicSquare(matrix, n);
}
private static void getMagicSquare13(int[][] m, int n) {
int x = 0, y = n / 2;
for (int i = 1; i <= n * n; i++) {
m[x][y] = i;
x -= 1;
y += 1;
if ( (y >= 0 && y < n) && x == -1) {
x = n - 1;
}
else if ( (x >= 0 && x < n) && y == n) {
y = 0;
}
else if ( (x == -1 && y == n) || (m[x][y] != 0)) {
x += 2;
y -= 1;
}
}
}
private static void printMagicSquare(int[][] m, int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (m[i][j] < 10) {
System.out.print(m[i][j] + " ");
}
else if (m[i][j] < 100) {
System.out.print(m[i][j] + " ");
}
else {
System.out.print(m[i][j] + " ");
}
}
System.out.println();
}
}
}
奇书阶的是在网上找的 偶数阶的本想自己编可是数学方面参悟不透
大家一起研究一下啊