重新想了想,不用区分奇数和偶数。代码如下:
import java.util.Scanner;
public class Prog14{
static int n = 7;
static int num = 1;//从1开始计数
static int b[][]=new int[n][n];
public static void main(String[] args){
for(int i = n;i>0;i=i-2){
setArray(getSize(i),n,b);
}
printB();
}
public static int getSize(int n){//计算每层长度
int sum = 2*(n+(n-2));
return sum;
}
public static int getX(int side,int n){//得到当前坐标x
return (n-side)/2;
}
public static void printB(){//打印数组
for(int x =0;x < n;x++){
for(int y =0;y < n;y++){
System.out.print(b[x][y]+" ");
}
System.out.println("\n");
}
}
public static void setArray(int s,int n,int b[][]){//对数组赋值
int top = (s+4)/4;//上
int other = top -1;//右、下
int left = top -2;//左
int x = getX(other,n);//数组x
int y = x;//数组y
for(int i = 1 ;i <= top;i++){//上
b[x][y] = num;
num++;
y++;
}
y--;
for(int i = 1 ;i <= other;i++){//右
x++;
b[x][y] = num;
num++;
}
for(int i = 1 ;i <= other;i++){//下
y--;
b[x][y] = num;
num++;
}
for(int i = 1 ;i <= left;i++){//左
x--;
b[x][y] = num;
num++;
}
}
} |