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?

2
  • You might want to read my blog post here for one possible approach using two unbounded stacks. Commented Nov 26, 2013 at 2:16
  • "Is there a simpler way to perform the function intended in the string?" Use the ScriptEngine as shown here. Commented Nov 26, 2013 at 2:18

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

1 Comment

Never knew that Java had an eval!
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.