/**
* *Test9--写一方法,打印等长的二维数组,要求从1开始的自然数由方阵的最外圈向内螺旋方式地顺序排列。 如: n = 4 则打印:
*/
public static void main(String[] args) {
print(4);
}
public static void print(int a){
int[][] arr = new int[a][a];
int count = 1;
int max = arr.length - 1;
int min = 0;
int x = 0;
int y = 0;
while(max > min){
while (y < max){
arr[x][y++] = count++;
}
while(x < max){
arr[x++][y] = count++;
}
while(y > min){
arr[x][y--] = count++;
}
while(x > min){
arr[x--][y] = count++;
}
if(max == min){
arr[x][y] = count;
}
x++;
y++;
max--;
min++;
}
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length; j++) {
System.out.print(arr[i][j] + "\t");
}
System.out.println();
}
} |
|