Home > Mobile >  Kotlin String to Integer And Calculate
Kotlin String to Integer And Calculate

Time:09-28

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.

CodePudding user response:

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.

CodePudding user response:

The actual process to convert a string is the next :

val intValue = "16".toInt()
assertEquals(16, intValue)

The opertaion you're trying to perform will require a concat once is converted, so to complete the real output would require to make 2 operation for each number indivual.

You can take a look to the documentation to understand how it works https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/to-int.html

  • Related