简体   繁体   中英

Modify a Global Variable with a Function?

In mousePressed, I need the value of aNumber, but I can't pass mousePressed(int aNumber).. so I need some sort of global to remain modified when theNumbers is called via javascript..

int number = 0;
int theNumbers(int aNumber) { //aNumber = 1, 2, or 3, from the javascript)

  println(number); // prints the correct number
  int number = aNumber; // set the global variable number equal to aNumber 
  return number;
}

void mousePressed() {
  aLongNumber = 10000000000;

  println(number); // prints 0 right now, should print the value of aNumber
  long numberLong = aLongNumber + (number * aLongNumber);
}

You are declaring local variable inside theNumbers() just remove int before number so your function would look like this:

int theNumbers(int aNumber) { //aNumber = 1, 2, or 3, from the javascript)

  println(number);
  number = aNumber; // removed int that made new local variable "number"
  return number;
}

Remove this line:

 int number = aNumber;

You copy the argument to the "number" variable and then return it. In fact, you are printing global variable "number" that is not changed in the code you posted anywhere, and then return the argument, that has nothing to do with calculations you have just done.

You probably wanted to modify the global parameter number and then return it, so make a change:

int theNumbers(int aNumber) {
   // calculations for number (based on aNumber? contains number=SOMETHING somewhere?)

   println(number); // prints the correct number    
   return number;
}

EDIT:

Just modify the global then. Remove the type from int number = aNumber; so you do not reinitialize the variable. In the end:

int theNumbers(int aNumber) {
   // calculations for number (based on aNumber? contains number=SOMETHING somewhere?)

   println(number); // prints the correct number    
   number = aNumber;
   return number;
}

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