群里看到一个题,感觉有趣就写了下,写的不太好,随便看看。
public static void main(String[] args) {
int n=6;
String[][] res=new String[n][n];
int x=0;//纵坐标
int y=0;//横坐标
int a =n-1;//横坐标一次循环最大值
int b=n-1;//纵坐标一次循环最大值
int i =0;//横坐标一次循环最小值
int j=-1;//纵坐标一次循环最小值
//获取输出数字前面要加几个0;
String s="";
for (int k = 0; k <(n*n+"").length(); k++) {
s=s+"0";
}
DecimalFormat df=new DecimalFormat(s);
//设置数值位置
for(int m=1;m<=n*n;m++){
String str=df.format(m);
res[x][y]=str;
if (y < a && x <= i) {
y++;//向右
continue;
}
if(y==a&&x==i){
j++;
}
if(y==a&&x<b){
x++;//向下
continue;
}
if(x==b&&y==a){
i++;
}
if(y>j&&x>=b){
y--;//向左
continue;
}
if(x==b&&y<=j){
a--;
}
if(x>i&&y==j){
x--;//向上
}
if(x==i&&y==j){
b--;
}
}
//输出
for(int c=0;c<n;c++){
for(int d=0;d<n;d++){
System.out.print(res[c][d]+" ");
}
System.out.println("");
}
}