求解java的奇数幻方

解决方案 »

  1.   

    import java.io.*;
    import java.util.*;
    public class TestMag {

    public void Magic(int n){
    int a[][]=new int[n][n];
    int row,col;
    row=0;col=(n-1)/2;
    a[row][col]=1;
    for(int j=2;j<=n*n;j++){
    if ((j-1)%n==0) {
    row=(row+1)%n;
    }else{
    row=(row+n-1)%n;
    col=(col+1)%n;
    }
    a[row][col]=j;
    }//end for
    for(row=0;row<n;row++){
    for(col=0;col<n;col++) System.out.print(a[row][col]+"  ");
         System.out.println();
    };
    }
    public static void main(String[]args){
    int n=0;
    TestMag tm=new TestMag();
        String sn;
    do{
    System.out.print("请输入一个奇数:");
    BufferedReader streami = new BufferedReader(
         new InputStreamReader(System.in));
    try {
    sn=streami.readLine();
    n=Integer.parseInt(sn);
        }
        catch (Exception ex) {
        }
    } while (n%2==0);
    tm.Magic(n);
    }
    }