[英]Convert 1d array to 2d array in JAVA
I am trying to input values from a 1d array into a 2d array in java. 我试图在Java中将1d数组中的值输入2d数组中。
This is what I have so far: 这是我到目前为止的内容:
int[] input2 = {
0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0
};
int[][] arr = new arr[3][4];
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
System.out.println("index" + ((i * arr.length) + j));
arr[i][j] = input2[(i * arr.length) + j];
//System.out.print(" " + arr[i][j]);
}
//System.out.println();
}
But what it outputs is: 但是它输出的是:
index0
index1
index2
index3
index3
index4
index5
index6
index6
index7
index8
index9
which means that I am getting the indexes wrong from 1d array. 这意味着我从一维数组中弄错了索引。 Where did I go wrong ? 我哪里做错了 ?
Your mistake is that in each step you multiply by the number of rows rather than the number of columns . 您的错误是,在每一步中,您乘以行数而不是列数 。
If you want to get to the first element of the second row, you have to skip all the elements of the first row first. 如果要转到第二行的第一个元素,则必须先跳过第一行的所有元素。 That would be 1 * arr[0].length
. 那将是1 * arr[0].length
。 So your method may work in an X by X array, but not in an X by Y array. 因此,您的方法可能适用于X by X数组,但不适用于X by Y数组。
It could well be filling in 2 dimensions, but ((i*arr.length) + j) is probably just adding the values. 它很可能是二维填充的,但是(((i * arr.length)+ j)可能只是在添加值。 I would add '+ ", "' in the middle of it to see what is actually getting output. 我将在其中间添加“ +”,“”以查看实际获得的输出。
在您的循环中尝试-
((i*arr[0].length) + j)
You should change your index formula from : 您应该将索引公式从更改为:
(i*arr.length) + j
to 至
(i*arr[i].length) + j
you can try this: 您可以尝试以下方法:
int count = 0;
for(int i=0; i< arr.length; i++)
{
for(int j=0; j<arr[i].length; j++)
{
//System.out.println("index" + ((i*arr.length) + j) );
arr[i][j] = input2[count++];
System.out.print(" " + arr[i][j]);
}
System.out.println();
}
Try 尝试
int[] input2 = {0,1,0,0,0,1,1,0,1,0,1,0};
int[][] arr = new arr[3][4];
for(int i=0; i< arr.length; i++)
{
for(int j=0; j<arr[i].length; j++)
{
System.out.println("index" + ((i*arr[i].length) + j) );
arr[i][j] = input2[(i*(arr[i].length)) + j];
//System.out.print(" " + arr[i][j]);
}
//System.out.println();
}
(Replaced ((i*arr.length) + j)
with ((i*arr[i].length) + j)
(用((i*arr[i].length) + j)
替换了((i*arr.length) + j)
((i*arr[i].length) + j)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.