0

I'm making a calculator program that can read in a string like this:

67+12-45

How can I perform the function that the string is intending to do? Here's what I've tried so far:

public static int calculate(String expression, int num1, int num2)
{
    int answer = 0;
    switch(expression)
    {
        case "+":
            if(answer != 0)
            {
                answer = answer + num1 + num2;
            }
            else
            {
                answer = num1 + num2;
            }
            break;
        case "-":
            if(answer != 0)
            {
                answer = answer + (num1 - num2);
            }
            else
            {
                answer = num1 - num2;
            }
            break;
        case "*":
            if(answer != 0)
            {
                answer = answer + (num1 * num2);
            }
            else
            {
                answer = num1 * num2;
            }
            break;
        case "/":
            if(answer != 0)
            {
                answer = answer + (num1 / num2);
            }
            else
            {
                answer = num1 / num2;
            }
            break;
        case "%":
            if(answer != 0)
            {
                answer = answer + (num1 % num2);
            }
            else
            {
                answer = num1 % num2;
            }
            break;
    }
    return answer;
}

Is there a simpler way to perform the function intended in the string?

Generalkidd
  • 579
  • 1
  • 8
  • 22
  • You might want to read my [blog post here](http://www.frischcode.com/2013/11/stack-unbound.html) for one possible approach using two unbounded stacks. – Elliott Frisch Nov 26 '13 at 02:16
  • *"Is there a simpler way to perform the function intended in the string?"* Use the `ScriptEngine` as shown [here](http://stackoverflow.com/a/7441804/418556). – Andrew Thompson Nov 26 '13 at 02:18

2 Answers2

3

the easiest way to achieve this is using eval, you can do this:

ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");        
Object result = engine.eval("67+12-45"); //you can insert any expression here
0

This talk describes an Object Oriented solution to this problem: http://youtu.be/4F72VULWFvc?t=7m40s

Essentially, you can parse the string into an expression tree that can be evaluated.

mattnedrich
  • 7,577
  • 9
  • 39
  • 45