以下是一个示例代码,演示了如何遍历一个二维数组并将其添加到一个新的一维数组中:
public class Main {
public static void main(String[] args) {
int[][] arr = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int[] newArr = flattenArray(arr);
// 打印新数组
for (int num : newArr) {
System.out.print(num + " ");
}
}
public static int[] flattenArray(int[][] arr) {
int numRows = arr.length;
int numCols = arr[0].length;
// 计算新数组的长度
int length = numRows * numCols;
// 创建新数组
int[] newArr = new int[length];
// 遍历二维数组并将元素添加到新数组中
int count = 0;
for (int i = 0; i < numRows; i++) {
for (int j = 0; j < numCols; j++) {
newArr[count] = arr[i][j];
count++;
}
}
return newArr;
}
}
运行上述代码,将得到以下输出:
1 2 3 4 5 6 7 8 9
这表示成功遍历了二维数组并将其添加到了新数组中。
上一篇:遍历二维数组并格式化两个索引。
下一篇:遍历二维数组并将值放入映射中