Modify a Global Variable with a Function?

2019-08-29 10:40发布

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

2条回答
我想做一个坏孩纸
2楼-- · 2019-08-29 10:53

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;
}
查看更多
Ridiculous、
3楼-- · 2019-08-29 10:59

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;
}
查看更多
登录 后发表回答