简体   繁体   中英

wrong array values

I have 2D array but if I change x coordinate, everytime I get wrong result.

  int[][] arr = {{0, 2, 0, 0, 1},{0, 2, 0, 0, 1},{0, 2, 0, 0, 1},{0, 2, 0, 0, 1},{0, 2, 0, 0, 1}};
int now, previous;

   for (int i = 1; i < 5; i++) {
    for (int j = 0; j < 5; j++) {
        now = arr[i][j];
        previous = arr[i-1][j];
        }
   }

The result of variable now is 0, 2, 0, 0, 1... Why I want to have only 2, 0, 0, 1 If I change i coordinate of variable for Example i = 1 the output is still 0, 2, 0, 0, 1... Do you know where is problem? Thanks

You need to put j = 1 instead of j = 0.

The i variable is iterating over the vectors that compose your array, while the j variable is iterating over each element of one of those vectors. You want to skip the first element of each vector, so you should change j to start at 1 instead of 0.

In any case, you are repeating the attribution inside a loop, and only the last value assigned to the variables will be kept. So assuming this is the original code you're using, you should remove the "for" loops and do the attributions directly, assuming your arr array will not change.

because i corresponds to the outer array in your example. what you have will print 0, 2, 0, 0, 1 four times. I gather what you want is to show 2, 0, 0, 1 five times... for that you should be doing

for (int i = 0; i < 5; i++) {
 for (int j = 1; j < 5; j++) {
     now = arr[i][j];
     previous = arr[i-1][j];
     }
}

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