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.

4
  • Is "+" the only operation possible in your input string, or do you want to support any arbitrary expression? Commented Sep 27, 2022 at 11:03
  • Not only + I will use expression like 11-2 or 11*2 any operator... Commented Sep 27, 2022 at 11:09
  • Does this answer your question? Can an integer in Kotlin be equal to an math expression? Commented Sep 27, 2022 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 objecthunter.net/exp4j Commented Sep 27, 2022 at 15:45

1 Answer 1

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.

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.