0

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];
3
  • 1
    Why isn't it working correctly? What exactly goes wrong? Commented Feb 13, 2018 at 22:10
  • Write down which indices you want each index in your string to map to. From there it should be pretty easy to write the code. Commented Feb 13, 2018 at 22:15
  • Duplicate of Map a 2D array onto a 1D array Commented Feb 13, 2018 at 22:17

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

Just the wrong indexing, otherwise you're good:

String text = "abcdefghijkl";
int rows = 4;
int cols = 3;
char boxChar[][] = new char[rows][cols];

for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {            
        boxChar[i][j] = text.charAt((i * cols) + j);
    }
}

//return boxChar[row][col];

System.out.println(boxChar[0]);
System.out.println(boxChar[1]);
System.out.println(boxChar[2]);
System.out.println(boxChar[3]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.