java用二维数组写定义两个数组,将这两个数组合并形成新的数组,打印新数组
时间: 2024-05-09 17:20:59 浏览: 59
下面是一个示例代码:
```java
public class MergeArrays {
public static void main(String[] args) {
int[][] array1 = {{1, 2}, {3, 4}};
int[][] array2 = {{5, 6}, {7, 8}};
int[][] mergedArray = mergeArrays(array1, array2);
printArray(mergedArray);
}
// 合并两个二维数组
public static int[][] mergeArrays(int[][] array1, int[][] array2) {
int rows = array1.length + array2.length;
int cols = array1[0].length;
int[][] mergedArray = new int[rows][cols];
for (int i = 0; i < array1.length; i++) {
for (int j = 0; j < cols; j++) {
mergedArray[i][j] = array1[i][j];
}
}
for (int i = 0; i < array2.length; i++) {
for (int j = 0; j < cols; j++) {
mergedArray[i + array1.length][j] = array2[i][j];
}
}
return mergedArray;
}
// 打印二维数组
public static void printArray(int[][] array) {
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.print(array[i][j] + " ");
}
System.out.println();
}
}
}
```
输出结果:
```
1 2
3 4
5 6
7 8
```
阅读全文