Search code examples
javastringkotlinformatint

How to convert an arithmetic expression of a string type to an integer?


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

fun main( args : Array<String>) {


    var str:String = "(%d + %d)"
    var str1:String

    var a:Int = 12
    var b:Int = 13

    str1 = String.format(str,12,13)
    var c:Int = str1.toInt()

   print(c)

}

Exception with stack trace is given below:

Exception in thread "main" java.lang.NumberFormatException: For input string: "(12 + 13)"
    at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
    at java.base/java.lang.Integer.parseInt(Integer.java:638)
    at java.base/java.lang.Integer.parseInt(Integer.java:770)
    at MainKotlinKt.main(mainKotlin.kt:13)

Please help me to solve.


Solution

  • kotlin .toInt() used for converting string to integer where string must be contain integer value. but you have used expression for converting string to integer.

    you can read more from here

    but if you want to evaluate an expression, then This can be done with the kotlin script engine.

    example:

    val engine = ScriptEngineManager().getEngineByExtension("kts")!!
    engine.eval("val x = 8")
    val result = engine.eval("x + 2")
    Assert.assertEquals(10, result)
    

    and you can get more information from here