views:

20

answers:

2

Hi Guys,

This is a follow up question from http://stackoverflow.com/questions/3238690/problem-with-array-assignment

I now have addcube done like so.. and all works as expected, when I print the array. but when I print the same index's AFTER assignment in another class It tells me their equal to 0. So the values are not 'saving'. Why is this? How would I correct this?

       public void addcube(float highx, float lowx, float highz, float lowz){
        //Constructing new cube...
System.out.println("f = " + f);
        Global.cubes++;
        float y = 1.5f;
        System.out.println("highx = " + highx + "lowx = " + lowx + "highz = " +         highz + "lowz = " + lowz);
        //FRONT
        Global.camObjCoord[Global.i] = highx;
        Global.i++;
        System.out.println("cube i = " + Global.i);
}

In both cases I'm printing like so...

    int p = 0;
            while(p < 72){
                System.out.println(Global.camObjCoord[p]);
                p++;
            }

Global.i = 0 at the beginning.

The only other places the array is being referenced is the following..

cubeBuff = makeFloatBuffer(Global.camObjCoord);

                FloatBuffer makeFloatBuffer(float[] arr) {
            ByteBuffer bb = ByteBuffer.allocateDirect(arr.length*4);
            bb.order(ByteOrder.nativeOrder());
            FloatBuffer fb = bb.asFloatBuffer();
            fb.put(arr);
            fb.position(0);
            return fb;
    }

There is no further refrences to the array in my code.

Thanks.

+1  A: 

My guess is that your code looks something like this:

System.out.println(Global.camObjCoord[Global.i]);
addcube(/* values here */);
System.out.println(Global.camObjCoord[Global.i]);

and it's printing out 0. Well, that's not printing out the same index after assignment, because Global.i changes value during addcube. For example, suppose Global.i is 3 before the call to addcube. The call to addcube will set Global.camObjCoord[3] to a value, but then set Global.i to 4, so the final line will print out Global.camObjCoord[4] - i.e. not the value which is just been set.

This sort of thing is precisely why global variables are a bad idea...

Jon Skeet
Code doesn't look like that, check Question again I updated.
Ulkmun
+2  A: 

I would seriously question your design. You're always refering to that Global class, which apparantly seems to be changed from everywhere, and hence you run into such problems (for instance previously with your NullPointerException).

Try seperate things clearly using encapsulation and do not just use one global state that is operated on by different classes. If classes strictly operate only on their own members then dependencies are reduced and it is much easier to track where data is manipulated.

inflagranti