user3047858
user3047858

Reputation: 31

Kotlin String to Integer And Calculate

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.

Upvotes: 0

Views: 408

Answers (1)

Niranjan Nlc
Niranjan Nlc

Reputation: 134

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.

Upvotes: 3

Related Questions