本帖最后由 田磊阳 于 2013-3-19 22:43 编辑
import java.util.Scanner;
class Demo{
public static void main(String[] args){
System.out.println("请输入九宫格的行列规模(只能是奇数的)");
Scanner n = new Scanner(System.in);
int N;
double d;
while (true){
d = n.nextDouble();
N = (int)d;
if ((d-N)>1.0E-4||N%2==0||N<0)
{System.out.println("输入出错,格局只能是正奇数。请重新输入");}
else break;
}
int[][] result = new int[N][N];
int row = 0;
int col = N/2;
for (int i=1; i<=N*N; i++){
result [row][col] = i;
row--;
col++;
if (row<0&&col>=N){col--;row+=2;}
else if (row<0){ row = N-1;}
else if (col>=N){col = 0;}
else if (result[row][col] != 0){col--;row+=2;}
}
for (int i=0; i<N; i++){
for(int j=0; j<N; j++){System.out.print(result[j]+"\t");}
System.out.println();
}
int[][] result2 = new int[N][N];
result2[N/2][N/2] = (N*N+1)/2;
row = 0;
col = N/2;
for (int i=1; i<=N*N/2; i++){
result2[row][col] = i;
result2[N-row-1][N-col-1] = N*N+1-i;
row--;
col++;
if (row<0){ row = N-1;}
else if (col>=N){col = 0;}
else if (result2[row][col] != 0){col--;row+=2;}
}
System.out.println();
for (int i=0; i<N; i++){
for(int j=0; j<N; j++){System.out.print(result2[j]+"\t");}
System.out.println();
}
}
}
|