java例程练习(东软笔试题[n阶平面魔方])

import java.util.Scanner;

public class MoFang {
	public static void main(String[] args) {
		System.out.println("输入行(列)数:");
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();

		int[][] a = new int[n][n];
		int i = 0;
		int j = n / 2;
		
		//算法精要
		for (int k = 1; k <= n * n; k++) {
			a[i][j] = k;
			
			if (k % n == 0) {
				i = (i + 1) % n;
			} else {
				i = (i - 1 + n) % n;
				j = (j + 1 ) % n;
			}
		}
		
		for (int k = 0; k < a.length; k++) {
			for (int r = 0; r < a[k].length; r++) {
				System.out.print(a[k][r] + "\t");
			}
			System.out.println();
		}
	}
}

你可能感兴趣的:(java例程练习(东软笔试题[n阶平面魔方]))