1

Possible Duplicate:
Evaluating a math expression given in string form

Sorry about the long (and also slightly strange :)) title, I couldn't think of a better title for it, but here goes.

I have been making a calculator in Java using a JFrame which has JButtons like a real calculator would. As you click the buttons, the calculation appears in a TextArea. When the 'equals' button is pressed, the whole calculation is taken from the TextArea and calculated. The problem I'm having is how to actually calculate the answer. This may sound a little weird, but say the calculation I'm getting is 36+45/22. How would I write the numbers into variables then tell the computer which operations to perform on the variables, and in what order. Can this be done with an infinite number of variables? Is there any way to do this? Thanks for your help.

Community
  • 1
  • 1
imulsion
  • 8,820
  • 20
  • 54
  • 84

3 Answers3

3

You could use ScriptEngine:

ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
System.out.println("result = " + engine.eval("36+45/22"));

Another option is Jep.

Reimeus
  • 158,255
  • 15
  • 216
  • 276
1

Try this, I use a simillar implementation. Works just great. :-D

Evaluate expression in java

Community
  • 1
  • 1
Mukul Goel
  • 8,387
  • 6
  • 37
  • 77
0

If you want to evaluate the expression yourself and not depend on external APIs such as ScriptEngine, you must parse the expression first. This parsing gives you an in-memory representation of the expression which you can then evaluate.

A common way to handle arithmetic expressions is a recursive descent parser. This kind of parser has the nice feature that it evaluates the parsed expression in-place in the parsing methods. An example for a recursive descent parser that does not depend on computer science's formal language theory can be found at http://www.savarese.org/articles/1998-2006/2001-05-Recursive_Descent_Parsing/

nd.
  • 8,699
  • 2
  • 32
  • 42