Filling a 2D array in Java

Arrays in Java are zero-based, which means they start at index zero, and range until index array.length-1.

Your code starts the row and column at 1—which means you’re skipping the initialization of row/column 0. That’s probably where at least some of the problems are coming from, since you’re using your 5×5 array (rows/columns 0,1,2,3,4) as a 4×4 array (rows/columns 1,2,3,4).

There’s also the fact that your Encrypt method doesn’t actually make any assignments to the array. You probably want to initialize it like this:

// NOTE: changed return type to void -- this is a side-effect-only method!
public void Encrypt(char Encrypt[][])
{
    // NOTE: use single-quotes for chars. double-quotes are for strings.
    char aChar="A";
    // NOTE: changed the starting loop values from `1` to `0`
    for (int row = 0; row < Encrypt.length; row++)
    {
        // NOTE: technically Encrypt.length works here since it's a square
        // 2D array, but you should really loop until Encrypt[row].length
        for (int column = 0; column < Encrypt[row].length; column++)
        {
            // NOTE: set each entry to the desired char value
            Encrypt[row][column] = aChar;
        }
    }   
}

There are several issues with your original code. Look at the NOTE entries in the comments for individual explanations.

Leave a Comment