0

I am dealing with the following code

fun main()
{
    var exp = "11+2"
    println(exp) // first statement
    println(exp.toInt()) // Second Statement
}

When I run the above code, My Aim to display the output, as 

11+2 // here 11+2 is a String
13 // Here the output I should get is 13 by adding 11+2 during run time, since I am converting the 11+2 to Integer, But I am getting error as

11+2
Exception in thread "main" java.lang.NumberFormatException: For input string: "11+2"
 at java.lang.NumberFormatException.forInputString (:-1) 
 at java.lang.Integer.parseInt (:-1) 
 at java.lang.Integer.parseInt (:-1) 

Can anyone Solve or provide solution to add during run time and get 13 as result.

  • Is "+" the only operation possible in your input string, or do you want to support any arbitrary expression? – k314159 Sep 27 '22 at 11:03
  • Not only + I will use expression like 11-2 or 11*2 any operator... – user3047858 Sep 27 '22 at 11:09
  • Does this answer your question? [Can an integer in Kotlin be equal to an math expression?](https://stackoverflow.com/questions/45094181/can-an-integer-in-kotlin-be-equal-to-an-math-expression) – k314159 Sep 27 '22 at 11:18
  • There are no standard library functions for this. You either need to implement the logic yourself or use a library such as https://www.objecthunter.net/exp4j/ – Tenfour04 Sep 27 '22 at 15:45

1 Answers1

3

Till date , it is not possible natively in kotlin. We have to code manually to evaluate arithmetic in string expressions like above. You can refer this link for reference.

Niranjan Nlc
  • 126
  • 1
  • 7