1

I am given:

    static String[] initStrings =
{
    "...../...\\",
    "..\\.......",
    "......./..",
    "..........",
    "........\\.",
    "..........",
    "..........",
    ".....\\../.",
    "..\\....../",
    ".........."
};

and something like this:

    static char[][] squares = 
{

};

Now, I need to write a method that will copy each character from each initStrings string into squares array. So far I have this:

    public static void initialize()
{
    int lengR = initStrings.length;
    int lengC = initStrings[0].length();
    squares = new char[lengR][lengC];
    for(int i=0; i<lengR;i++)
    {
        squares[i] = initStrings[i].toCharArray();
    }
}

I am very new to this and I'm pretty sure my for loop is wrong.. I don't see any errors so far, but I just don't understand how my initialize method would work. How do you convert 1-dimensional String array to 2-dimensional Char array? Please help me out.. :(

2 Answers 2

2

There is nothing wrong with your for loop: a 2D array in Java is a 1D array of 1D arrays; String's toCharArray returns one of these 1D arrays. Your for loop puts them together into an array of arrays, so the result is a 2D array.

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

Comments

0

You could also do it with 2 for loops addressing each entry in squares:

for (int i=0; i<lengR; i++) {
    for (int k=0; k<lengL; k++) {
        squares[i][k]=initStrings[i].charAt[k];
    }
}

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.