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

Java中2x2数组复制到4x6数组的结果异常问题排查求助

二维数组复制问题排查

我是Java编程新手,本次作业要求将一个2x2二维数组的内容复制到4x6二维数组的中间区域。我编写了代码,但输出结果与预期不符,不清楚问题所在,希望有人能帮我排查代码中的问题。

我的代码

public class Main {
    
    public static void main(String[] args) {
        
         int[][] a = {{11,12},{21,22}};
         int[][] b = new int[4][6];
    
         System.out.print("a[][] = \n");
         output(a);   
         System.out.print("\nb[][] = \n");
         copy(a,b);
    }
    
    static void output(int[][] x) {
        for(int i=0; i<x.length;i++) {
            for(int j=0;j<x[i].length;j++) {
                System.out.printf(" %2d ", x[i][j]);
            }
            System.out.println();
        }
    }
    
    static void  copy(int[][] source, int[][] destination) {
        for(int i=0;i<source.length;i++) {
            destination[i]= new int[source.length];
            System.arraycopy(source[i], 0, destination[i+1], 2, destination[i].length);
        }
        output(destination);
    }
}

预期输出

a[][]
 11 12
 21 22
b[][]
  0  0  0  0  0  0
  0  0 11 12  0  0
  0  0 21 22  0  0
  0  0  0  0  0  0

实际输出

a[][] = 
 11  12 
 21  22 

b[][] = 
  0   0 
  0   0 
  0   0  21  22   0   0 
  0   0   0   0   0   0 

问题分析与修正

你的copy方法存在两个关键错误:

  • 错误修改目标数组的行结构:
    代码里的destination[i]= new int[source.length];完全多余,甚至会破坏原本的4x6数组结构——它把目标数组的前两行(索引0、1)重新初始化为长度为2的数组,这就是实际输出里前两行只有两个0的原因。

  • 数组复制的参数错误:
    System.arraycopy的最后一个参数是要复制的元素个数,你用了destination[i].length,但这个值在错误初始化后变成了2,导致第一次复制的逻辑完全失效,只有第二次循环的内容被正确部分展示。

修正后的copy方法如下:

static void copy(int[][] source, int[][] destination) {
    // 遍历源数组的每一行,复制到目标数组的中间两行(索引1、2)
    for(int i = 0; i < source.length; i++) {
        // 从目标行的索引2开始,复制源数组当前行的全部元素
        System.arraycopy(source[i], 0, destination[i + 1], 2, source[i].length);
    }
    output(destination);
}

修正后的完整代码

public class Main {
    
    public static void main(String[] args) {
        
         int[][] a = {{11,12},{21,22}};
         int[][] b = new int[4][6];
    
         System.out.print("a[][] = \n");
         output(a);   
         System.out.print("\nb[][] = \n");
         copy(a,b);
    }
    
    static void output(int[][] x) {
        for(int i=0; i<x.length;i++) {
            for(int j=0;j<x[i].length;j++) {
                System.out.printf(" %2d ", x[i][j]);
            }
            System.out.println();
        }
    }
    
    static void copy(int[][] source, int[][] destination) {
        for(int i = 0; i < source.length; i++) {
            System.arraycopy(source[i], 0, destination[i + 1], 2, source[i].length);
        }
        output(destination);
    }
}

运行这段代码即可得到你预期的输出结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 10:50:28