I am writing an expression evaluator for arithmetic expressions. I have treated parentheticals in expressions such as: 25 * (7 + 3) + 19 as "sub-expressions" and have called methods recursively in order to evaluate them. The only way that I have been able to keep track of variable values across my recursive objects is to make the necessary variables static - but it feels as though this is sort of anti-encapsulation. I have tried using return statements lots of places, but the variable values still aren't retained. Also, I haven't found a discussion of recursion in Java in the books I have (Head First Java and Core Java, book 1). Could anyone suggest somewhere I could get some information on this?
Joined: Jan 29, 2003
The generic answer is you hold all state for the current level of recursion in local variables. Show us some of what you have written. I'm pretty sure we'll be able to give you enough hints to get you going again.
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Joined: Apr 29, 2007
Thanks very much for your offer - and I'll be happy to send the code for comments and criticism. Please let me know.
But I think I might not have been very clear. The code works - meaning that I can give it a messy input expression and get the correct answer returned; it also has error messages for stuff like unbalanced parentheses. I'm doing this as a way to learn object orientation using Java as the vehicle - object orientation came in while I was raising & home-schooling my son, so I missed out when it was fresh. So when I was whining about needing something to do, because I have no confidence that I've learned something until I can actually write code, my (obnoxious) son suggested an expression evaluator. I have 3 classes and an enum in it and since I'm quite new at this it's probably pretty crude as well as being long. I asked the question because I'm all sorts of uncertain about whether I'm doing something crudely that more experienced folks can do more prettily or efficiently ...
Joined: Sep 08, 2004
I could not make a head or tail of your second message! However what ever little I understood of your problem is that you want to save some values across different recursive calls.
Stan is right that "you hold all state for the current level of recursion in local variables" and for holding data across levels, you can use static variables!
Hope I didn't get your question too wrong!!!
Joined: Mar 22, 2005
Any global data you need to retain might also be put into an appropriate data structure (maybe a Stack) that is passed as a parameter of the recursive calls.