Kotlin中如何将字符串类型的算术表达式转换为整数?

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

这是我在 运行 这段代码之后的代码,我遇到异常:

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

堆栈跟踪异常如下:

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)

您无法在 kotlin 或 java 中对字符串表达式中的算术求值。使用库(如 exp4j, Javaluator, and SEpl) or write your own (refer to this thread)。