方阵的主对角线之上称为“上三角”。
请你设计一个用于填充n阶方阵的上三角区域的程序。填充的规则是:使用1,2,3….的自然数列,从左上角开始,按照顺时针方向螺旋填充。
例如:当n=3时,输出:
1 2 3
6 4
5
当n=4时,输出:
1 2 3 4
9 10 5
8 6
7
当n=5时,输出:
1 2 3 4 5
12 13 14 6
11 15 7
10 8
9
程序运行时,要求用户输入整数n(3~20)
程序输出:方阵的上三角部分。
要求格式:每个数据宽度为4,右对齐。
要求考生把所有类写在一个文件中。调试好后,存入与考生文件夹下对应题号的“解答.txt”中即可。相关的工程文件不要拷入。请不要使用package语句。
另外,源程序中只能出现JDK1.5中允许的语法或调用。不能使用1.6或更高版本。
请你设计一个用于填充n阶方阵的上三角区域的程序。填充的规则是:使用1,2,3….的自然数列,从左上角开始,按照顺时针方向螺旋填充。
例如:当n=3时,输出:
1 2 3
6 4
5
当n=4时,输出:
1 2 3 4
9 10 5
8 6
7
当n=5时,输出:
1 2 3 4 5
12 13 14 6
11 15 7
10 8
9
程序运行时,要求用户输入整数n(3~20)
程序输出:方阵的上三角部分。
要求格式:每个数据宽度为4,右对齐。
要求考生把所有类写在一个文件中。调试好后,存入与考生文件夹下对应题号的“解答.txt”中即可。相关的工程文件不要拷入。请不要使用package语句。
另外,源程序中只能出现JDK1.5中允许的语法或调用。不能使用1.6或更高版本。
[[len=4],[len=3],[len=2],[len=1]]
之后for(;;) 在里面写跳出
public class Test {
public static void main(String[] args) throws Throwable {
for (int i=3; i<10; i++) {
printTriangle(i);
System.out.println();
}
} public static void printTriangle(int n) {
int[][] num = new int[n][n];
for (int cnt=1, row=0, col=0, left=0, right=n, top=0, bottom=n, f=0; cnt<=n*(n+1)/2; cnt++) {
if (f == 0) { //从左到右方向
if (col < right) { //没到右边界
num[row][col++] = cnt;
} else { //到达右边界,改变方向
f = 1;
right--;
row = top + 1;
col = right - 1;
num[row++][col--] = cnt;
}
} else if (f == 1) { //从右上到左下方向
if (row < bottom) { //没到左下边界
num[row++][col--] = cnt;
} else { //到达左下边界,改变方向
f = 2;
bottom--;
row = bottom-1;
col = left;
num[row--][col] = cnt;
}
} else if (f == 2) { //从下到上方向
if (row > top) { //没到上边界
num[row--][col] = cnt;
} else { //到达上边界,改变方向
f = 0;
top++;
left++;
right--;
bottom--;
row = top;
col = left;
num[row][col++] = cnt;
}
}
} for (int i=0; i<n; i++) {
for (int j=0; j<n-i; j++) {
System.out.printf("%2d ", num[i][j]);
}
System.out.println();
}
}
}