import java.util.Scanner;
public class LuoXuan2 {
public static void main(String[] args) {
System.out.println("请输入螺旋方阵维度:");
Scanner sc =new Scanner(System.in);
int x =sc.nextInt();
// 计数器
int count = 1;
// 设定数组
int[][] arr = new int[x][x];
// 用来设定循环次数,控制每次能够少打印一个元素
int n = 1, i = 0, j = 0;
if(x%2!=0){
arr[x/2][x/2]=x*x;
}
while (count <x*x) {
for (; j < arr[i].length - n; j++) {
arr[i][j] = count;
count++;
}
for (; i < arr.length - n; i++) {
arr[i][j] = count;
count++;
}
for (; j > n - 1; j--) {
arr[i][j] = count;
count++;
}
for (; i > n - 1; i--) {
arr[i][j] = count;
count++;
}
i=n;
j=n;
n++;
}
ArrayPrint(arr);
}
public static void ArrayPrint(int[][] arr) {
// int n=0;
for (int j2 = 0; j2 < arr.length; j2++) {
for (int k = 0; k < arr[j2].length; k++) {
System.out.print(arr[j2][k] + "\t");
}
System.out.println();
}
}
}
|
|