Skip to content
Advertisement

why does this for loop always only adds 1’s to the array [closed]

I made a two dimensional String array in java, and in the last row, which has the index of 6, I want put in numbers from 1 to 7 on every second space of the array. My code looks like this:

    for(int i = 1; i < columns; i += 2) {
        int number = 1;
        fieldArray[6][i] = Integer.toString(number);
        number++;
    }

My problem is that the output of the last row of the 2 dimensional array looks like this:

null 1 null 1 null 1 null 1 null 1 null 1 null 1 null 

I don’t understand why, the way I understood for loops is that in the first iteration it starts with an index of 1, adds the content of the variable number which is converted to a String to fit in the String array, then the variable number is increased by one, next iteration, index is 3, and number is 2, but the content of index 3 is one as well, why?

The nulls in the array are there on purpose, I want to add something different using the same kind of for loop but with a different offset later.

Advertisement

Answer

Here you are defining the number variable each time, for each iteration setting it to 1.
You should define number outside the for loop, before it.
Something like this:

int number = 1;
for(int i = 1; i < columns; i += 2) {
    fieldArray[6][i] = Integer.toString(number);
    number++;
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement