Got an array:
JavaScript
x
String[] array = song.split("");
[W, U, B, W, U, B, A, B, C, W, U, B]
I need to convert it in two dimension:
JavaScript
String[][] arr = new String[4][3];
[[W, U, B], [W, U, B], [A, B, C], [W, U, B]]
Below code:
JavaScript
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[j].length; j++) {
arr[i][j] = array[j];
}
}
gives the result:
JavaScript
[[W, U, B], [W, U, B], [W, U, B], [W, U, B]]
How to get:
JavaScript
[[W, U, B], [W, U, B], [A, B, C], [W, U, B]]
Advertisement
Answer
You’re assigning the wrong value to arr[i][j]
:
JavaScript
for (int i = 0; i <arr.length ; i++) {
for (int j = 0; j <arr[j].length ; j++) {
arr[i][j] = array[i * arr[j].length + j];
}
}