How would I Evaluate a certain formula?

后端 未结 4 1314
旧时难觅i
旧时难觅i 2021-01-27 09:24

I have a multidimension arrayList and I ask the user for a formula and than I evaluate it. The problem is that I get user input like this:

  ((a1+a2)/12)*a3


        
相关标签:
4条回答
  • 2021-01-27 09:32

    You will need to turn the formula into something like a Binary Expression Tree. This should be not that difficult.

    Then you will need to traverse this tree to evaluate the expression value at the start and each time a value in the arrayList changes. Concentrate first on building the tree and getting correct values when you evaluate it. Don't forget negative numbers and variables! Watching the arrayList for changes should be trivial after that.

    0 讨论(0)
  • 2021-01-27 09:44

    A possibility is write a sort of parser. It's better to use a binary tree structure to represent an expression, rather than a list.

    Each non-leaf node is an operation and every leaf is operand.

    tree

    0 讨论(0)
  • 2021-01-27 09:46

    An alternative to Heisenbug's suggestion is to try Dijkstra's shunting-yard algorithm. Instead of relying on a tree structure, you use stacks and queues. The advantage is that these data structures involved are not terribly complicated. The downside is that any errors in implementing the algorithm could be easily missed, as you need to thoroughly understand the operations involved to know if your implementation is correct.

    0 讨论(0)
  • 2021-01-27 09:49

    Personally, I'd try really hard to avoid all the parsing stuff, and look for an EL library that allows you to use your own variable resolver. All you'd need to do then is hook up the variables to your backing model. (In your case, splitting on word/letter boundary, and looking up cell contents.)

    This would also allow you to include arbitrary functions by simply exposing them to the EL engine. Something like OGNL, MVEL, etc. might be a good starting point. Seems much easier.

    0 讨论(0)
提交回复
热议问题