Java function changing input

Posted by Doodle on Stack Overflow See other posts from Stack Overflow or by Doodle
Published on 2010-04-26T09:27:30Z Indexed on 2010/04/26 9:33 UTC
Read the original article Hit count: 266

Filed under:
|
|

I would like to go from one number to another. For example if I started at 6 and my goal was 10 I want a function that on every pass would bring me from 6 towards 10 or if I had the number 14 and my goal was 9 it would count down from 14 towards 9.So far I have (this is written in Processing a Java Api but there is essentially no difference from regualr Java, draw is just a continuous loop)

int x=100;
void draw(){
  x=towards(x,10);
  println(x);

}

int towards(int current ,int target){
  if(current!=target){
    if (current <target){
      current=current+1;
    }
    else {
      current=current-1;
    }
  }
  return current;
}

this gives me the results I would like but I would like to have everything in side of the towards() function. When I replace X with a variable it of course resets it self to the static variable.

To sum it up how can I pass a variable to a function and have that variable thats been passed change on every subsequent pass. I have looked into recursion as a solution but that of just brings me to a final solution. I can pass the count to an array but wouldn't like to do that either.

© Stack Overflow or respective owner

Related posts about java

Related posts about functions