4

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.

Ashish Karn
  • 1,127
  • 1
  • 9
  • 20
  • 1
    See [data structures - Expression evaluation in java - Stack Overflow](https://stackoverflow.com/questions/19926777/expression-evaluation-in-java) –  Jul 05 '20 at 06:20

2 Answers2

1

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

Mahamudul Hasan
  • 2,745
  • 2
  • 17
  • 26
0

Firstly your code is nor right and secondly if you are tring to convert math expression in kotlin then I will say kotlin doesn't have any inbuilt function to evaluate math expression neither str1.toInt() will help you in this.

toInt() is used to convert string to integer. for example "10".toInt() = 10. So, I will suggest you to do manually after extracting required values from extression.

Ashish Karn
  • 1,127
  • 1
  • 9
  • 20