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)
  • 3
    There's no native way to parse a mathematical expression. You need to manually parse it yourself or use a library like `exp4j`. – Tenfour04 Mar 09 '22 at 13:34
  • Does this answer your question? [How to evaluate a math expression given in string form?](https://stackoverflow.com/questions/3422673/how-to-evaluate-a-math-expression-given-in-string-form) – kcode Mar 09 '22 at 19:06

1 Answers1

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).

kcode
  • 352
  • 1
  • 2
  • 14