You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin字符串转整数并计算:解决NumberFormatException问题

计算字符串形式的算术表达式

问题代码

fun main()
{
    var exp = "11+2"
    println(exp) // first statement
    println(exp.toInt()) // Second Statement
}

预期输出

11+2
13

实际错误

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)

错误原因

toInt()方法仅能转换纯数字组成的字符串,无法识别包含运算符的表达式。"11+2"里的+属于非数字字符,调用toInt()必然抛出NumberFormatException。

解决方案

方案1:手动解析简单表达式(仅支持加减)

适用于仅包含单个加减运算符的场景,通过拆分字符串提取操作数和运算符后计算:

fun main() {
    val exp = "11+2"
    println(exp)
    
    // 定位运算符位置
    val operatorPos = exp.indexOfFirst { it == '+' || it == '-' }
    if (operatorPos != -1) {
        val leftNum = exp.substring(0, operatorPos).toInt()
        val operator = exp[operatorPos]
        val rightNum = exp.substring(operatorPos + 1).toInt()
        
        val result = when (operator) {
            '+' -> leftNum + rightNum
            '-' -> leftNum - rightNum
            else -> 0
        }
        println(result)
    }
}

方案2:使用脚本引擎支持复杂表达式

如果需要支持乘除、多运算符等复杂表达式,可以借助Java的脚本引擎直接执行表达式:

import javax.script.ScriptEngineManager

fun main() {
    val exp = "11+2"
    println(exp)
    
    val scriptEngine = ScriptEngineManager().getEngineByName("JavaScript")
    val result = scriptEngine.eval(exp)
    println(result)
}

这个方法能处理大部分常见算术表达式,但注意如果表达式来自不可信来源,存在脚本注入风险,且性能略低于手动解析。

内容的提问来源于stack exchange,提问作者user3047858

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 04:55:18