开发者

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

开发者 https://www.devze.com 2022-12-07 21:19 出处:网络
This is my code after running this piece of code, I am getting exception: fun main() { var str = "(100 + 50)/2"

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

    fun main() {
    var str = "(100 + 50)/2"
    
    var sum = str.toInt()
    
    println(sum)
    }

Exception with stack trace is given below:

Exception in thread "main" java.lang.NumberFormatException: For 开发者_如何学编程input string: "(100 + 50)/2"
 at java.lang.NumberFormatException.forInputString (:-1) 
 at java.lang.Integer.parseInt (:-1) 
 at java.lang.Integer.parseInt (:-1)


You cannot evaluate arithmetic in string expressions natively in kotlin or java. Either use a library (like exp4j, Javaluator, and SEpl) or write your own (refer to this thread).

0

精彩评论

暂无评论...
验证码 换一张
取 消