将数据从一维数组转移到二维数组中,Java。

huangapple go评论70阅读模式
英文:

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 &lt;array.length ; i++) {
    for (int j = 0; j &lt;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 &lt;array.length ; i++) {
    for (int j = 0; j &lt;array[j].length ; j++) {
        array[i][j] = arr[indexForArr];
        indexForArr = indexForArr + 1;
    }
}

huangapple
  • 本文由 发表于 2020年4月10日 21:52:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/61141732.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定