0

How do I interpret a mathematical expression such as:
x^2+8x+16

into a code that Java understands such as
x*x+8*x+16 ?

I know that just parsing the first code using a ScriptEngine won't work because it doesn't know how to properly evaulate 8x. What do I do!??

iptq
  • 657
  • 1
  • 7
  • 15
  • 1
    define your own parsing rules. use regular expressions to parse the string. and combine them according to your business logic. – Juvanis Oct 25 '12 at 06:25
  • 1
    Did you read http://stackoverflow.com/questions/3252895/convert-mathematical-string-to-int/3252967 ? It's about evaluation, but the libs might work for you as well... – home Oct 25 '12 at 06:25
  • 1
    You could roll your own parser. If the expression cannot contain parentheses, then it's 1) split by `+` and `-`, 2) split by `*`,`/` and a digit-alpha boundary, 3) split by a `^` – John Dvorak Oct 25 '12 at 06:27
  • An **expression tree** may be of assistance to you. – Zéychin Oct 25 '12 at 16:57
  • Write a context-free grammar for mathematical expressions (regular expressions won't suffice once you have parentheses), then generate a parser for it using some tool. For bonus points you can try to parse `3 sin x cos^2 x`. – starblue Oct 25 '12 at 19:38

0 Answers0