Generalkidd
Generalkidd

Reputation: 579

Java calculate numbers in a string

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?

Upvotes: 0

Views: 139

Answers (2)

mattnedrich
mattnedrich

Reputation: 8072

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.

Upvotes: 0

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

Upvotes: 3

Related Questions