我需要不使用arraycopy并按顺序附加2个2D数组,首先是arr1然后是arr2,如下所示:
int[][] arr1 = {{1,2},{7,9,10}};
int[][] arr2 = {{3,5,7,9},{16,10,11}};
int[][] arr3 = append(arr1,arr2);
result should be:
1 2
7 9 10
3 5 7 9
16 10 11
我已经尝试过:
public static int[][] append(int[][] arr1, int[][] arr2) {
int [][] arr3 = new int [arr1.length + arr2.length][];
for (int i=0; i<arr1.length; i=i+1) {
for (int j=0; j<arr1[i].length; j=j+1) {
arr3[i][j] = arr1[i][j];
}
}
for (int x=arr1.length; x<arr3.length-2; x=x+1) {
int a=0;
for (int y=0; y<arr2[a].length; y=y+1) {
arr3[x][y] = arr2[a][y];
a=a+1;
}
}
return arr3;
}
但是我在行上得到一个空指针异常'arr3 [i] [j] = arr1 [i] [j];'我能做什么?感谢您的帮助!
您有两个问题:
arr3[i]
的长度a
变量。声明它需要超出第一个循环,而递增它需要超出第二个循环(在第一个循环的末尾)。将您的代码更改为类似这样的内容:
public static int[][] append(int[][] arr1, int[][] arr2) {
int [][] arr3 = new int [arr1.length + arr2.length][];
for (int i = 0; i < arr1.length; i = i+1) {
arr3[i] = new int[arr1[i].length];
for (int j = 0; j < arr1[i].length; j = j+1) {
arr3[i][j] = arr1[i][j];
}
}
int a = 0;
for (int x = arr1.length; x < arr3.length; x = x+1) {
arr3[x] = new int[arr2[a].length];
for (int y = 0; y < arr2[a].length; y = y+1) {
arr3[x][y] = arr2[a][y];
}
a = a+1;
}
return arr3;
}