【#文档大全网# 导语】以下是®文档大全网的小编为您整理的《JAVA完成九宫格程序代码》,欢迎阅读!

完成九宫格程序代码
import java.util.Scanner; class NinePalace{
public static void main(String[] args){
// 定义 N 为九宫格的行列数,需要输入
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; //列 初始位置,因为列由0开始,故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 i++){
for(int j=0; j System.out.println(); }
//我个人的填格方式
int[][] result2 = new int[N][N]; //为免冲突,重新 new 一个数组 result2[N/2][N/2] = (N*N+1)/2; //先把中间值赋予中间位置
row = 0; //定义行及列的初始赋值位置。之前赋值的for对两个值有影响,故需重新定位
col = N/2;
for (int i=1; i<=N*N/2; i++){ result2[row][col] = i;
//下面这句是把跟 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 i++){
}
} }
for(int j=0; jSystem.out.println();
本文来源:https://www.wddqxz.cn/b1612fcea1c7aa00b52acb25.html