Home > Mobile >  Why is this array not filling properly
Why is this array not filling properly

Time:11-30

This code is supposed to fill mCifrado, a String[][], with random String[] called vCifrado. vCifrado is randomized by desordenar(), which swaps 2 random letters a given number of time.

As you can see, the top for loop fills it and prints its content, which results in (in this particular randomized case) this

enter image description here

Which is, technically, what I'm looking for. But this is not what is really being stored in the array, and this is proved by the second for loop, which is the exact same from the top one but without the two lines of code that fill the 2D array mCifrado, which prints this (again, in this particular random case)

enter image description here

For some reason mCifrado is storing the last row in every row, and i dont really know why, since it's supposed to be printing the same as the correct example I showed before.

Does anyone know why is it storing the text like that? I've been looking at it for a while but I really can't find a reason

public void cifrarMatriz() {
    for (int i = 0; i < mCifrado.length; i  ) {
        desordenar(vCifrado, 500);
        mCifrado[i] = vCifrado;
        for (int c = 0; c < vCifrado.length; c  ) {
            System.out.print(mCifrado[i][c]);
        }
        System.out.println("");
    }
    System.out.println("");
    for (int i = 0; i < mCifrado.length; i  ) {
        for (int c = 0; c < vCifrado.length; c  ) {
            System.out.print(mCifrado[i][c]);
        }
        System.out.println("");
    }
}

I've tried storing the text in some different way, for example rotating the rows and copying vCifrado in mCifrado[0] 5 times, so it goes back to the original position, but that results in the same problem.

CodePudding user response:

Actually the last row is the only one row you have. A String[] is an object which is passed by reference.

So you shuffle the values in that array and store a reference into your String[][] matrix, and this repeats several times. Since there is only one String[], shuffling the values impacts all rows at the same time. And when you print all the rows they all look the same.

Your first loop will have to look like this:

for (int i = 0; i < mCifrado.length; i  ) {
    desordenar(vCifrado, 500);
    mCifrado[i] = new String[vCifrado]; // here you actually create new rows
    for (int c = 0; c < vCifrado.length; c  ) { //...which then need to get populated
        mCifrado[i][c] = vCifrado[c];
    }
}

Since there is no data modification between your first and second loop, of course the data is still in memory and will give the same result. That's the whole point of storing something in memory.

  •  Tags:  
  • java
  • Related