本帖最后由 shenqi 于 2013-5-9 11:49 编辑
- package cn.itcast.itheima2;
- public class CrossTest {
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- String[][] cross = getCross(2);
-
- for(int i=0;i<cross.length;i++){
-
- for(int j=0;j<cross.length;j++){
- System.out.print(cross[i][j]+" ");
- }
- System.out.println();
- System.out.println();
-
- }
- }
-
- public static String[][] getCross(int num){
-
- if(num > 30 || num == 0)
- throw new IllegalArgumentException("无效的参数(0<num<30)");
- //数组的大小
- int size=9;
- //每次增长4
- int increase = 4;
- //生成二维数组的大小
- for(int i=1;i<num;i++){
- size +=increase;
- }
- //创建一个二维数组
- String[][] cross = new String[size][size];
- for(int i=0;i<cross.length;i++){
- for(int j=0;j<cross.length;j++){
- cross[i][j] = " ";
- }
- }
-
- //定义十字的初始位置
- int x = size/2-2;
- int y = size/2-2;
- //中间的十字 无论数组多大都是固定的大小
- for(int i=0;i<5;i++,x++,y++){
- cross[x][size/2] = "0";
- cross[size/2][y] = "0";
- }
- //初始化外边边界形状
- int w = size/2-4;
- int n = size/2-4;
-
- int e = size/2+4;
- int s = size/2+4;
-
-
- //外边形状循环的次数
- for(int i=1,/*初始化转角*/corner=2,/*tmp控制里层循环次数*/tmp=2;i<=num;i++,tmp+=3,w-=2,n-=2,e+=2,s+=2){
-
- //边界
- border(w,1, tmp, cross);
- border(n,0, tmp, cross);
- border(e,1,tmp, cross);
- border(s,0,tmp, cross);
-
- //转角
- //左上角
- corner(cross, size/2-corner,size/2-corner,0);
- //右上角
- corner(cross, size/2-corner,size/2+corner,1);
- //右下角
- corner(cross, size/2+corner, size/2-corner,2);
- //左下角
- corner(cross, size/2+corner,size/2+corner,3);
- corner+=2;
- }
-
- return cross;
- }
-
- private static void border(int j,int flag,int control,String[][] cross){
-
- int left = cross.length/2;
- int right = cross.length/2;
-
- //0表示横坐标, 1表示纵坐标
- switch(flag){
- case 0 :
- for(int i=0;i<control;i++,left--,right++){
- cross[j][left] = "0";
- cross[j][right] = "0";
- }
- break;
- case 1 :
- for(int i=0;i<control;i++,left--,right++){
- cross[left][j] = "0";
- cross[right][j] = "0";
- }
- break;
- }
-
- }
-
-
- //加入转角的位置
- private static void corner(String[][] cross,int x,int y,int flag){
-
- switch(flag){
- case 0:
- cross[x][y] = "0";
- cross[x][y-1] = "0";
- cross[x][y-2] = "0";
- cross[x-1][y] = "0";
- cross[x-2][y] = "0";
- break;
- case 1:
- cross[x][y] = "0";
- cross[x][y+1] = "0";
- cross[x][y+2] = "0";
- cross[x-1][y] = "0";
- cross[x-2][y] = "0";
- break;
- case 2:
- cross[x][y] = "0";
- cross[x][y-1] = "0";
- cross[x][y-2] = "0";
- cross[x+1][y] = "0";
- cross[x+2][y] = "0";
- break;
- case 3:
- cross[x][y] = "0";
- cross[x][y+1] = "0";
- cross[x][y+2] = "0";
- cross[x+1][y] = "0";
- cross[x+2][y] = "0";
- break;
- }
-
- }
-
- }
复制代码 1个小时完成了!~不过代码还有冗余!~总体算完成!~
|