奇数阶幻方的Java源程序,偶数的怎么弄呢??

 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();
    }
  }

}


奇书阶的是在网上找的  偶数阶的本想自己编可是数学方面参悟不透

大家一起研究一下啊

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值