请你设计一个用于填充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或更高版本。
import java.io.*;
public class Triangle
{
public class Triangle
{
public static void main(String[] args) throws IOException
{
new CarryOut().Execute();
}
}
class CarryOut
{
}
class CarryOut
{
public void Execute() throws IOException
{
BufferedReader ch=new BufferedReader(new InputStreamReader(System.in));
System.out.print("请输入一个数:");
int n=Integer.parseInt(ch.readLine()); // n == 4
int[][] nn=new int[n][n];
int number=1;
int t=0;
if(n==1)
{
System.out.print(1);
return ;
}
for(int i=0;i<n;i++) // 0 =< i < 4
{
boolean Judge=true;
for(int x=t;x<n-2*t-1;x++) //x=1 1<3
{
Judge=false;
nn[t][x]=number++;
}
for(int y=t,tt=n-t*2-1;y<n-2*t-1;y++) // y=1 y<2
{
Judge=false;
nn[y][tt]=number++;
tt--;
}
for(int z=n-2*t-1;z>=t+1;z--)
{
Judge=false;
nn[z][t]=number++;
}
if(Judge && n!=2)
{
nn[t][t]=number;
break;
}
if(t>n/2)
{
break;
}
t++;
}
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(nn[i][j]!=0)
{
System.out.print(String.format("%-5d", nn[i][j]).toString());
}
}
System.out.println() ;
}
}
}
}