使用函数修改全局变量?

时间:2014-05-27 10:30:11

标签: java canvas global-variables processing argument-passing

在mousePressed中,我需要aNumber的值,但是我不能通过mousePressed(int aNumber)..所以当通过javascript调用Numbers时我需要某种全局来保持修改..

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 个答案:

答案 0 :(得分:2)

您要在theNumbers()内声明局部变量,只需在int之前删除number,这样您的函数将如下所示:

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

答案 1 :(得分:1)

删除此行:

 int number = aNumber;

您将参数复制到"数字"变量然后返回它。实际上,您正在打印全局变量" number"您在任何地方发布的代码中没有更改,然后返回参数,这与您刚刚完成的计算无关。

您可能想要修改全局参数number然后将其返回,因此请进行更改:

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

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

编辑:

然后修改全局。从int number = aNumber;中删除类型,这样就不会重新初始化变量。最后:

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

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