2

I'll make my question to the point. I have a string with some value and operators. Let's take an example of

4 * 24 + Math.sqrt(36) - 5

So if I do Integer.parseInt() it crashed. On further search I found out that I have to use a parser. But they were for command line java whereas mine is in android.

So my question is how do I convert this string "4 * 24 + Math.sqrt(36) - 5" into an integer which calculates the result? Also will this method include the Math.sqrt () function?

Thanks.

EDIT 1:

In response to hacker13ua

When I try your MAVEN method I get this error. Any Idea Why?

Caused by: java.lang.StringIndexOutOfBoundsException: length=1; regionStart=0; regionLength=3

My Code:

final String foo = "4 * 24 + Math.sqrt(36) - 5";
                    Object i = MVEL.eval(foo);
                    String in = i.toString();
                    Toast.makeText(MainActivity.this,String.valueOf(in).toString(), Toast.LENGTH_LONG).show();

And this is in my gradle build file

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:22.2.0'
compile 'org.mvel:mvel2:2.2.7.Final'

}

Thanks

2

1 Answer 1

2

You can use javascript engine.

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class Main
{
    public static void main(final String[] args) throws ScriptException
    {
        final ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
        final ScriptEngine engine = scriptEngineManager.getEngineByName("javascript");
        final String foo = "4 * 24 + Math.sqrt(36) - 5";
        System.out.println(engine.eval(foo));
    }
}

Or you can use MVEL. Maven dependency:

<dependency>
    <groupId>org.mvel</groupId>
    <artifactId>mvel2</artifactId>
    <version>2.2.7.Final</version>
</dependency>

Your code:

import org.mvel2.MVEL;

public class Main
{
    public static void main(final String[] args)
    {
        final String foo = "4 * 24 + Math.sqrt(36) - 5";
        System.out.println(MVEL.eval(foo));
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

System.println Is command line java. However for the maven one 1 need my pc. I'm on travel and thus am using an ide on phone. Give me a couple of days and I'll reply to the maven answer. However the first part I believe is meant for command line. I saw this answer to another question and I couldn't import the classes. That's why
Please see my edits above. Also how do you use the javax method. Do I have to add some API. If so how?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.