作业帮 > 综合 > 作业

写一个Java程序一个数让它从内减小循环一个正方形

来源:学生作业帮 编辑:神马作文网作业帮 分类:综合作业 时间:2024/11/12 18:18:15
写一个Java程序一个数让它从内减小循环一个正方形
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
写一个Java程序一个数让它从内减小循环一个正方形
package demo;
public class Cat {
/**
 * @param args
 */
public static void main(String[] args) {
 int number = 5;
 int[][] arys = printCircle(number);
 for (int i = 0; i < number; i++) {
 for (int j = 0; j < number; j++) {
 System.out.print(arys[i][j] + "\t");
 }
 System.out.println();
 }
}
// 1 2 3 4 5
// 16 17 18 19 6
// 15 24 25 20 7
// 14 23 22 21 8
// 13 12 11 10 9
private static int[][] printCircle(int number) {
 int[][] ary = new int[number][number];
 int rightLen;
 int downLen;
 int leftLen;
 int upLen;

 int rightRow = 0;
 int rightCol = 0;
 int leftRow = number - 1;
 int leftCol = number - 1;
 int downRow = 1;
 int downCol = number - 1;
 int upRow = number - 2;
 int upCol = 0;
 int digit = 1;

 while(number > 0){

 rightLen = number;
 downLen = number - 1;
 leftLen = number - 1;
 upLen = number - 2;

 //Step 1: print to right
 for(int i = 0, temp = rightCol; i < rightLen; i++){
 ary[rightRow][temp++] = digit++;
 }

 //Step 2: print to down
 for(int j = 0, temp = downRow; j < downLen; j++){
 ary[temp++][downCol] = digit++;
 }

 //move left
 for(int m = 0, temp = leftCol - 1; m < leftLen; m++){
 ary[leftRow][temp--] = digit++;
 }

 //move up
 for(int n = 0, temp = upRow; n < upLen; n++){
 ary[temp--][upCol] = digit++;
 }

 number = number - 2;

 //increas/decrease the row and column
 rightRow++;
 rightCol++;
 downRow++;
 downCol--;
 leftRow--;
 leftCol--;
 upRow--;
 upCol++;

 }

 return ary;

}
}