用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 

相反。

您做错了几件事:

  • 用源大小的空数组替换目标行
  • 使用目标长度而不是源长度

以下是它的外观。

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);
}

我包含了一个更通用的解决方案如下:

并不是所有的数组都适用于这种拷贝。如果复制成功与否,我会返回一个布尔值。以下是一些指导原则。

  • 复制到中心意味着上方和下方有相同数量的未填充行,或者左侧或右侧有相同数目的未填充列。这可以通过从最大维度中减去最小维度来确定,并查看余数除以2是否等于零。如果是,则复制应该成功,并返回true。否则,将打印一条信息性消息,并返回false
  • 每行或每列的起始位置是通过从较长的维度中减去较短的维度并除以2来确定的
  • 循环在源数组上迭代,而System.arraycopy执行复制到目标的工作,增加目标行索引
int[][] arr = { { 11, 12}, { 21,22}};
int[][] dest = new int[4][6];
if (copyToCenter(arr, dest)) {
for (int[] rows : dest) {
System.out.println(Arrays.toString(rows));
}
}

打印

[0, 0, 0, 0, 0, 0]
[0, 0, 11, 12, 0, 0]
[0, 0, 21, 22, 0, 0]
[0, 0, 0, 0, 0, 0]

复制方法。

static boolean copyToCenter(int[][] source, int[][] destination) {
if ((destination.length - source.length) % 2 != 0
|| (destination[0].length - source[0].length) % 2 != 0) {
System.out
.println("Arrays do not lend themselves to required copy");
return false;
}

int firstCol = (destination[0].length - source[0].length) / 2;
int destRow = (destination.length - source.length) / 2;
for (int[] sourceRow : source) {
System.arraycopy(sourceRow, 0, destination[destRow++],
firstCol, source[0].length);
}
return true;
}

最新更新