简体   繁体   中英

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.

The first thing i want to mention is that u shouldn't declare your variables (a, b....) static. Maybe u got hit by a mean side effect after creating two instances of Sparse. Try to define them as non static and report if it still wont work.

Best regards Thomas

Try removing this from each call to b[] if you want to access b[] as static.

Also, are you sure you are not overwritting b[] anywhere else in the code? This is most likely the issue because of the public static declaration. Try making it private and removing static and see if you still have the issue.

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++;
    }
}

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