[Java] 纯文本查看 复制代码 import javax.swing.JOptionPane;
public class Circle {
int[][] numArray;
int record = 1;// 记录每层的起始数字
int stepF = 0;// 每层的起始下标
int stepE = 0;// 每层的终止下标
int reduce = 0;// 用于记录减小量
public static void main(String args[]) {
new Circle().process();
}
public void setNum(int num) {// 递归的为二维数组赋值
if (num > 0) {// 只要层数是正数继续赋值
for (int i = stepF; i < stepE; i++) {// 为每层的第一列和最后一列赋值
numArray[i][stepF] = record;
numArray[i][stepE - 1] = record + 3 * (num - 1) - 2 * reduce;
reduce++;
record++;
}
reduce = 1;
for (int i = stepF + 1; i < stepE - 1; i++) {// 为每层的第一行和最后一行赋值
numArray[stepE - 1][i] = record;
numArray[stepF][i] = record + 3 * (num - 1) - 2 * reduce;
reduce++;
record++;
}
reduce = 0;
stepF++;
record = record + 2 * (num - 1);// 得到下一层的起始量
stepE--;
setNum(num - 2);// 每递归一次每层边上的数字量减小2
} else// 当边数含有的数字量非正时退出递归
return;
}
public void process() {// 将数组中的数字按行列的形式输出
String s = JOptionPane.showInputDialog("输入正方形矩阵的变长:");
int num = Integer.parseInt(s);
numArray = new int[num][num];
String space = "";
stepE = num;
setNum(num);
for (int i = 0; i < num; i++) {
for (int j = 0; j < num; j++) {
if (numArray[i][j] < 10 && j > 0) {// 保证输出是个正方形,不会因为是一位数或者2位数影响效果
space = " ";
} else
space = " ";
System.out.print(numArray[i][j] + space);
}
System.out.println();// 输入完一行后要换行
}
}
}
|