A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© shuren2015 中级黑马   /  2015-2-28 21:31  /  612 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

9、 写一方法,打印等长的二维数组,要求从1开始的自然数由方阵的最外圈向内螺旋方式地顺序排列。
一开始想的很复杂,想通也就那么回事
  1. package blog;

  2. public class ArrayDemo {

  3.         public static void main(String[] args) {
  4.                 // TODO Auto-generated method stub
  5.                 test(7);
  6.         }
  7.         public static void test(int a){
  8.                 int[][] x=new int[a][a];
  9.                 int count=1;
  10.                 //
  11.                 for(int m=0;m<a>>1;m++){
  12.                         //往右初始化
  13.                         for(int b=m;b<a-m;b++){
  14.                                 x[m][b]=count++;
  15.                                 //往下初始化
  16.                         }for(int c=m+1;c<a-1-m;c++){
  17.                                 x[c][a-1-m]=count++;
  18.                                 //往左初始化
  19.                         }for(int d=a-1-m;d>=m;d--){
  20.                                 x[a-1-m][d]=count++;
  21.                                 //往上初始化
  22.                         }for(int e=a-2-m;e>m;e--){
  23.                                 x[e][m]=count++;
  24.                                 //当a为奇数时,发现最中间的少了,直接补丁补上(上面的代码自己都不敢看了)
  25.                         }if(a%2==1){
  26.                                 int h=a/2;
  27.                                 x[h][h]=a*a;
  28.                         }
  29.                        
  30.                 }
  31.                 //遍历打印该二维数组
  32.                 for(int p=0;p<a;p++){
  33.                         for(int t=0;t<a;t++){
  34.                                 System.out.print(x[p][t]+"\t");
  35.                         }
  36.                         System.out.println();
  37.                 }
  38.         }
  39. }
复制代码
                       

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马