简体   繁体   中英

Trouble filling 2D array with values obtained from method

I'm having trouble filling a matrix with values I get by iterating through a method. I want to use a 3x3 matrix and then fill it with the values I obtain by iterating my method from 0 to 8. My idea was a for-loop but it does not work unfortunately. I would be glad if someone could help or has a link where I can look that up.

int[][] matrix = new int[3][3];

for (int i = 0; i < matrix.length; i++){
  for (int j = 0; j < matrix[i].length; j++){
    for(int a = 0; a < 9; a++) {
      matrix[i][j] = fields.get(a).getSign().getFieldValue();
    }       
  }
}

Correct me if im wrong. the way i understood your question was you want to fill the matrix like this:

012
345
678

in that case you can do the first 2 forloops and add some maths, to get the correct numbers on every position:

int[][] matrix = new int[3][3];

for (int i = 0; i < matrix.length; i++) {
  for (int j = 0; j < matrix[i].length; j++) {
    matrix[i][j] = i * matrix[i].length + j;
  }
}

the way this works is for every row (i) you multiplay the rownumber by the rows length (the ammount of columns) and add the current column to it

To iterate through a two dimensional field (eg a matrix), you can use two for loops:

int dimension = 3;
int [][] matrix = new int [dimension][dimension];

for (int i = 0; i < dimension; i++){
   for ( int j = 0; j < dimension; j++){
      matrix[i][j] = fields.get(i).get(j);
   }
}

I don't exactly know how you want to retrieve the values, but your current call looks suspicious to say the least :-) It will simply assign the same value to all ints in column j .

If you simulate your loop, this is what it looks like

i -> 0
    j -> 0
        matrix[0][0] -> loop over all values from field

this way you would be putting the fields.get(8) into each index in your matrix.

@Alan's answers show how to properly loop and fill a 2d matrix from a 1d matrix

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM