You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java嵌套for循环打印中心递减数字方阵代码调试求助

嵌套循环打印对称数字方阵调试

问题背景

实现嵌套循环打印数字图案的功能,输入图案尺寸size时,需要输出中心值为1、向外逐层递增到size的对称数字方阵。以size=3为例,预期输出为:

3 3 3 3 3 
3 2 2 2 3
3 2 1 2 3
3 2 2 2 3
3 3 3 3 3

现有Java代码运行后输出残缺,实际输出为:

3 2 1 
3 2 1 
3 2 1
3 2 
3 

现有代码如下:

System.out.print("Enter the length of the pattern size: ");
int size = scan.nextInt();
System.out.println();
for (int row=size*2-1; row >= 1; row--) { 
    for (int col=size*2-1; col >= 1; col--) {
        if (col <= size && row >= size-col+1 )
            System.out.print(col + " ");
    }
    System.out.println();
}

问题定位

现有代码的逻辑缺陷有两点:

  • 内层循环仅在col <= size(即方阵左半侧列)时执行输出,右半侧列没有匹配的输出逻辑,直接导致每行输出长度不足
  • 判断规则仅覆盖了方阵左上三角区域的数值映射,没有处理对称的右半、下半区域的坐标和数值对应关系,最终输出为残缺的三角形状

正确实现思路

这类对称圈层数字方阵的通用规律是:方阵中任意位置要打印的数字,等于该位置到方阵四条边的最小距离 + 1。不需要拆分多段分支判断左右、上下区域,直接按这个规律计算每个位置的数值即可。
修正后的可运行代码:

System.out.print("Enter the length of the pattern size: ");
int size = scan.nextInt();
int sideLen = size * 2 - 1; // 对称方阵的总边长
System.out.println();
// 逐行遍历
for (int row = 1; row <= sideLen; row++) {
    // 逐列遍历当前行
    for (int col = 1; col <= sideLen; col++) {
        // 分别计算当前坐标到四个边界的距离
        int distTop = row - 1;
        int distBottom = sideLen - row;
        int distLeft = col - 1;
        int distRight = sideLen - col;
        // 取四个距离的最小值,加1就是当前位置的数字
        int minDist = Math.min(Math.min(distTop, distBottom), Math.min(distLeft, distRight));
        System.out.print((minDist + 1) + " ");
    }
    System.out.println();
}

如果需要保留原有倒序遍历行列的写法,只需要把内层循环里的条件判断替换为上述距离计算逻辑即可,遍历顺序不影响最终输出结果。

内容的提问来源于stack exchange,提问作者Kurogx

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.30 10:36:24