Skip to content
Advertisement

Appending a string into 2d Array Java

I have a string containing the following:

String text = "abcdefghijkl"

I want to put it in a 2d array so there will be 4 rows of 3

this is currently what I have, its not working correctly though:

char boxChar[][] = new char[4][3];
        int j,i;

        for (i = 0; i<4; i++)
        {
            for (j=0; j<3; j++)
            {            

                boxChar[i][j] = text.charAt((i+1)*(j));

            }

        }

        return boxChar[row][col];

Advertisement

Answer

It looks like you got the indexes mixed up. I added some print statements to your original code with a modification to get the right char in your charAt instruction.

    String text = "abcdefghijkl";

    char boxChar[][] = new char[4][3];
    int j,i;

    for (i = 0; i<4; i++)
    {
        for (j=0; j<3; j++)
        {            

            boxChar[i][j] = text.charAt(i*3+j);
            System.out.print(boxChar[i][j]);
        }
        System.out.println();

    }

Sometimes it can be helpful to jot it down on a piece of paper if it’s not lining up how you expected.

With your input string, the positions on a 1d array are

a    b    c    d    e    f    g    h    i    j    k    l
0    1    2    3    4    5    6    7    8    9   10   11

As you loop through to get the box array (matrix), your outer loop indicates that you want four rows and three columns, in other words

a    b    c
d    e    f
g    h    i
j    k    l

so for the first element, a, its position is (0,0), b is at (0,1) and so on. Your charAt(position) has to map the 2d positions to their corresponding 1d positions.

Advertisement