1

I only want to fill in the top and bottom row of an uninitialised array:

for (int i = 0; i < ROWS; i++) {
    for (int j = 0; j < COLUMNS; j++) {
        if (i == 0 || i == (ROWS - 1)) {
            values[i][j] = i;
        }
    }
}

However, when I do so, it fills in all the rows in between with 0:

0000000000
0000000000
0000000000
0000000000
4444444444

Why is this the case?

dave
  • 11,641
  • 5
  • 47
  • 65
doctopus
  • 5,349
  • 8
  • 53
  • 105

2 Answers2

2

The default value for any int in Java is zero (0). So any that are left unset will have this value. This is the case whether it's a single int or an array of them. The consequence of this is that the rows which are untouched by your code contain zeroes.

dave
  • 11,641
  • 5
  • 47
  • 65
2

Just access only the top and bottom rows explicitly:

for (int i=0; i < ROWS; i+=ROWS-1) {
    for (int j=0; j < COLUMNS; j++) {
        values[i][j] = i;
    }
}

This avoids iterating every row unnecessarily. Note that the zeroes you are seeing may be the default value for an int array.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360