英文:
transfer data from one dimensional array in two-dimensional array java
问题
假设我有一个一维数组 array
int[] arr = new int[]{1,2,3,4,5,6};
我需要将这个 arr
中的所有数据转移到二维数组 array
int[][] array = new int[2][3];
以下是代码:
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
array[i][j] = arr[i * array[i].length + j];
}
}
返回结果:
[[1,2,3], [4,5,6]]
如何实现?
英文:
Assume I have one dimensional array
int[] arr = new int[]{1,2,3,4,5,6)
and I need transfer all data from this arr
in two-dimensional array
int[][]array = new int[2][1];
bellow code:
for (int i = 0; i <array.length ; i++) {
for (int j = 0; j <array[j].length ; j++) {
array[i][j] = arr[i];
}
}
return result:
[[1], [2]]
I need:
[[1,2,3], [4,5,6]]
How to achieve it?
答案1
得分: 1
你的二维数组太小了。为了得到你想要的输出,它的形状需要是 2 行 3 列。
int[][] array = new int[2][3];
你还需要改变构建数组的循环。它必须分别跟踪原始数组的索引和二维数组的索引。
int indexForArr = 0;
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[j].length; j++) {
array[i][j] = arr[indexForArr];
indexForArr = indexForArr + 1;
}
}
英文:
Your 2d array is too small. To get the output you want, it needs to have a shape of 2 by 3.
int[][] array = new int[2][3];
You will also need to change the loop that builds the array. It has to keep track of the index for the original array separately from the indices of the 2d array.
int indexForArr = 0;
for (int i = 0; i <array.length ; i++) {
for (int j = 0; j <array[j].length ; j++) {
array[i][j] = arr[indexForArr];
indexForArr = indexForArr + 1;
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论