This week's book giveaway is in the OCPJP forum. We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line! See this thread for details.
I'm busy trying to code a calculator and I started with what I deemed to be the most difficult bit...precedence.
My idea is to have a recursive function that will analyze a string and return the expression with the highest precedence.I can then use this method in any calculate methods I write at a later stage.(Will also have to figure out how to remove brackets etc..)
Now what I am trying to figure out is with regards to using parentheses.I am trying to define the condition that marks a certain expression as having the highest priority.So far I have written different utility methods to assist me like methods to calulate how many opening/closing brackets precede/succeed a given char in a string.
What should my final test look like??
Would a subString starting from the char having the most preceding opening brackets and ending on the char having the most succeeding closing brackets be the innermost expression??No...it wouldn't...could someone assist me in defining the criteria for the innermost expression??
How would I determine the expression with the highest priority in:
i don't know for sure, but... i think you need to assign precedence to the OPERATOR, not the character right after the paren... if you take this expression:
start parsing, and count how many levels deep you are
now, do the operation with the highest priority. If there is more than one with equal depth, you need to follow the basic rules of the order of operations - exponents first, then mult. and div. in order left to right, then add/sub in order from left to right.
our deepest operator is 3, so we do that first
4 - 6 = -2
now do everything that is two levels deep, then one, then 0.
There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Duran Harris wrote:Nice...I got shown how to implement this as a stack!Feel like a bit of a retard though considering I spent the whole day trying to get it right and someone else implemented it in 10min!
Ha , that's nothing. I've been known to spend an entire weekend unsuccesfully trying to get implement a dozen lines of code in a recursive algorithm.