Search code examples
javaglobal-variablesnested-loopssparse-matrix

Global Java array setting values to 0


I've a slight problem. I'm taking every element in a sparse matrix and putting it into a 1d array named 'b[]'. For example:

00070
00400
02000
00050
10000

Becomes: 0007000400020000005010000

The code below works in that at a given point within the inner-most loop b[] has the correct value as shown below. My problem is that outside of the inner-most loop b[] has a value of:

b[] = 0000000000000000000000000

I cannot understand what I'm missing. It should also be noted that b[] is globally defined, and instantiated within the constructor of this class. The problem is that I'm trying to use this 1d array in another function, and every element within the array is set to 0.

public void return1dSequence() {

    // Create paired objects (Pair class).

    for (int i = 0; i < a.length; i++) {

        for(int j = 0; j < a[i].length; j++) {
            this.b[i] = a[i][j];

            // System.out.print(b[i]);
            if (this.b[i] == 0) {
                pos += 1;
            } else {
                value = this.b[i];
                ml.add(new Pair(pos, value));
                pos += 1;
            }
        }
    }
}

Thanks in advance for any replies,

Andre.


Solution

  • You're filling in b[i] for indexes i of your outer loop...

    Each time in the inner loop, you overwrite b[i] with value a[i][j].

    Last value of a[i] array is always zero.

    That's why your b array is zero.

    What you want is probably:

    int counter = 0;
    for (int i = 0; i < a.length; i++) {
        for(int j = 0; j < a[i].length; j++) {
            b[counter] = a[i][j];
            counter++;
        }
    }