0

I want to create operator in string and show the value as int.

// ex:

val str= "1+2*3" , print out -> "1+2*3"

// i want:

print out -> 7

however i tried to create kotlin code like:

val str= "${1+2*3}" or val str= "1+2*3".toInt

but all this don't work.

any help???

1
  • 1
    You're going to need some kind of a parser here. Btw, it's 7, not 9. Commented Mar 27, 2019 at 21:21

1 Answer 1

1

You need to have some kind of parsers to achieve that.

Few examples

http://mathparser.org/

The advantage with the above is that you can perform any kind of calculation like below.

Expression e = new Expression("( 2 + 3/4 + sin(pi) )/2");
double v = e.calculate()

Or by using the Java inbuilt Scriptengine.

ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
String foo = "1+2*3";
System.out.println(engine.eval(foo)); //prints 7
Sign up to request clarification or add additional context in comments.

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.