0

This is my code after running this piece of code, I am getting exception:

    fun main() {
    var str = "(100 + 50)/2"
    
    var sum = str.toInt()
    
    println(sum)
    }

Exception with stack trace is given below:

Exception in thread "main" java.lang.NumberFormatException: For input string: "(100 + 50)/2"
 at java.lang.NumberFormatException.forInputString (:-1) 
 at java.lang.Integer.parseInt (:-1) 
 at java.lang.Integer.parseInt (:-1)
2
  • 3
    There's no native way to parse a mathematical expression. You need to manually parse it yourself or use a library like exp4j. Commented Mar 9, 2022 at 13:34
  • Does this answer your question? How to evaluate a math expression given in string form? Commented Mar 9, 2022 at 19:06

1 Answer 1

1

You cannot evaluate arithmetic in string expressions natively in kotlin or java. Either use a library (like exp4j, Javaluator, and SEpl) or write your own (refer to this thread).

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.