• Post Reply Bookmark Topic Watch Topic
  • New Topic

Variable scope issue  RSS feed

 
Jonathan Haybok
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I had some issues with the count variable when making this Hailstone Sequence application. I got it to work, but am wondering if someone can explain the scoping issues involved with increasing count in the displayNext() method. Debugging shows that the count resets to 1 every time the while loop iterates. How would I allow the displayNext() method to properly set the variable (instead of my compromise of just iterating count within the while loop)?
 
Ralph Cook
Ranch Hand
Posts: 479
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think this may be a "by value" issue, not a scoping issue.

You pass in a variable named count to the displayNext() routine. That variable is passed "by value", which is to say a copy of it is passed to and used by the routine, and the original value of it is not affected by the routine. There is no other way to pass an integer to a method in Java.

You could return the count value from display next, then call it as count = displayNext(start, count)

This would allow displayNext to know the starting value of the variable (from being passed in) and to return it to the calling routine (as a return argument). You would need to define displayNext() as a method that returned an int if you did this.

You can also do it by defining count as an instance variable; in this case, you would not need to pass it in. I've got the quickie code to do that here:



I had to guess that you wanted count incremented each time you called displayNext.

In this code, the method is incrementing the static class variable, and so it is not local to the routine and will maintain its value regardless of whether the code is executing the routine. And it had to be static because both the routines calling it are static; you don't have an instance of your class in this program.

I hope that clears things up. I know it's a confusing subject at the beginning.

rc
 
Jonathan Haybok
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Awesome! Thanks for the thorough explanation. I knew java was pass-by-value, but I guess the notion took a while to sink in. The static declaration makes sense to me too now.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!