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

Java生成0和1同心交替正方形矩阵输出异常求助

问题排查与修复方案

原代码存在的问题

  • 存在冗余的用户输入逻辑:需求是生成0和1组成的同心交替正方形矩阵,不需要提前让用户输入所有矩阵元素,这一步不仅多余,还会干扰后续生成逻辑的验证。
  • 分层绘制逻辑混乱:内层1、0边框的绘制使用了多层嵌套循环,循环变量的起止条件设计错误,导致不同层边框的绘制顺序和值覆盖出错,无法生成符合要求的交替效果。

修复后的完整代码

import java.util.Scanner;
public class LEDLights {
    public static void main(String[] args) {
        int size;
        System.out.println("Enter the size of an array:");
        Scanner sc=new Scanner(System.in);
        size=sc.nextInt();
        int myarr[][]=new int[size][size];
        
        // 直接按同心规则生成矩阵
        for(int i = 0; i < size; i++){
            for(int j = 0; j < size; j++){
                // 计算当前坐标所在的层数,最外层为0层,向内逐层+1
                int layer = Math.min(Math.min(i, size-1 -i), Math.min(j, size-1 -j));
                // 偶数层填1,奇数层填0,符合交替要求
                myarr[i][j] = layer % 2 == 0 ? 1 : 0;
            }
        }

        System.out.println("LED lights blinking\n");
        for(int i = 0; i < size; i++){
            for(int j = 0; j < size; j++){
                System.out.print( myarr[i][j]+ " ");
            }
            System.out.println();
        }
    }
}

验证效果

输入size为8时,程序输出和你给出的预期结果完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 09:57:03