1

I am trying to read String objects into a 2d array, from a char array, using column-major ordering:

This is what I've tried:

int x = 0;
for (int column = 0; column < matrix[0].length; column++) {//cols
     for (int row = 0; row < matrix.length; row++, x++) {//rows
         if(matrix[row][column] == null) {
             if (x < ciphertextCharacters.length) {
                 matrix[row][column] = Character.toString(inputChars[x]);
             }
         }
    }
}

given an input array (inputChars = ['t', 't', 'g', 'e', 'i', 's', 'n']) the resulting 2D array should be:

+---+----+----+
| t | e  |  s |
+---+----+----+
| t | i  |  n |
+---+----+----+
| g | *  |  * |
+---+----+----+

Note that before this code runs, the "*" strings are already in the array - and that's why I'm only adding new values when the index is null.

Currently, the resulting 2D array I'm getting is:

+---+----+----+
| t | e  |  n |
+---+----+----+
| t | i  |null|
+---+----+----+
| g | *  |  * |
+---+----+----+

Which is not what I need.

1
  • you increment your x too often. move x++ from the loop declaration to the end of the if block Commented Oct 19, 2016 at 9:44

1 Answer 1

2

The problem is that you place inputChars[x] into matrix[row][column] based on the outcome of a condition, but x is incremented unconditionally:

for (int row = 0; row < matrix.length; row++, x++) {
//                                            ^^^

Replacing unconditional increment in the loop with a conditional increment on assignment should fix this problem:

for (int row = 0; row < matrix.length; row++) {
    ...
    matrix[row][column] = Character.toString(inputChars[x++]);
    ...
}
Sign up to request clarification or add additional context in comments.

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.