1

I am having a problem where, after performing a simple mathematical operation on the elements of an array, I return this array and receive only what was changed in the specific function.

You may be thinking, "Great. That's what's supposed to happen." You are correct, but let me give another situation: I call functionA below, then I call functionB. Instead of getting 1 1 1 as the output, I get 0 3 -2, the exact same as functionB without the call to functionA.

Here's the example's code:

public static int[] position = new int[3];  //This array is filled 
                                            //with [0,0,0] using a for-loop

    public static int[] functionA(int[] position){

        position[0] =+ 1;  //=+ operator use
        position[1] =- 2;  //=- operator use
        position[2] =+ 3;

        return position;
    }

    public static int[] functionB(int[] position){

        position[0] =+ 0;
        position[1] =+ 3;
        position[2] =- 2;

        return position;
    }

    functionA(position);
    functionB(position);

    System.out.println(myPosition[0]);  //0
    System.out.println(myPosition[1]);  //1
    System.out.println(myPosition[2]);  //-2

I do not understand where I went wrong. Am I using the =+ or =- operators incorrectly or am I returning the array incorrectly, or is there something I am totally missing?

Any help is appreciated.

nmagerko
  • 6,586
  • 12
  • 46
  • 71
  • Just as an aside: If you intend to modify the array itself, there's no need to return it. In fact, returning an array tends to imply that you're generating a new one, and that the original array won't be modified. – cHao Apr 02 '12 at 00:08
  • I see. I have reflected this in my code (not above). Thank you! – nmagerko Apr 02 '12 at 00:10
  • 1
    Expanding on the answers below: `=+5` will be interpreted as `= (+5)` and `=-5` would be interpreted as `= (-5)`. – Jeffrey Apr 02 '12 at 00:12
  • @Jeffrey Ah. That was a sad mistake on my part. Thank you. – nmagerko Apr 02 '12 at 00:13

2 Answers2

3

Use += instead of =+, and -= instead of =-.

Take a look on this SO question: What is the difference between a += b and a =+ b , also a++ and ++a?

Community
  • 1
  • 1
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
1

It's +=, not =+. The same for subtraction.

iehrlich
  • 3,572
  • 4
  • 34
  • 43