开发者

Java array to multi dimensional

开发者 https://www.devze.com 2023-01-21 04:26 出处:网络
Is it possible to take an array o开发者_C百科f say 100 chars and turn it into a 2d array of 10*10?Here you go

Is it possible to take an array o开发者_C百科f say 100 chars and turn it into a 2d array of 10*10?


Here you go

char[] chars = ("01234567890123456789012345678901234567890123456789" + 
                "01234567890123456789012345678901234567890123456789")
                .toCharArray();

char[][] char2D = new char[10][10];

for (int i = 0; i < 100; i++)
    char2D[i / 10][i % 10] = chars[i];

Now the this code...

System.out.println(Arrays.deepToString(char2D).replaceAll("],","],\n"));

...prints the following

[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]


Iterate throughout your list of 100 chars and divide it amongst the 10*10, Modulus (%) will probably be very useful.

You could use 2 nested for loops to assign the chars of the array to the appropriate element.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号