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

Kotlin控制台输入处理报错:NumberFormatException异常求助

Fixing the NumberFormatException in Your Kotlin Console Input Code

Hey there! Let's break down why you're hitting that NumberFormatException and get your code working smoothly.

What's Causing the Crash?

Your code uses str.split(" ") to split the input string into parts, but here's the catch:

  • If your input has leading/trailing spaces or consecutive spaces, this split will create empty string elements in the resulting list.
  • When you try to convert an empty string "" to an integer with toInt(), it throws the NumberFormatException you're seeing.

Looking at your input string, it's likely there's an extra space hidden at the start, end, or somewhere in the middle that's triggering this issue.

How to Fix It

Here are a few straightforward solutions to handle this properly:

Solution 1: Split on Any Whitespace (Cleanest Approach)

Instead of splitting on a single space, use a regex that matches one or more whitespace characters (spaces, tabs, etc.). This automatically ignores extra spaces and avoids empty strings entirely:

fun main(args: Array<String>) {
    println("I'm running")
    val str = readLine()
    var sum = 0
    str?.let { input ->
        // Split on one or more whitespace characters
        val arr = input.split("\\s+".toRegex()).map(String::toInt).toIntArray()
        for (num in arr) sum += num
        println(sum)
    }
    println("not running anymore")
}

Solution 2: Explicitly Filter Out Empty Strings

If you prefer to stick with splitting on single spaces, add a filter to remove empty strings before converting to integers:

fun main(args: Array<String>) {
    println("I'm running")
    val str = readLine()
    var sum = 0
    str?.let { input ->
        val arr = input.split(" ")
            .filterNotEmpty() // Strip out any empty strings from the split result
            .map(String::toInt)
            .toIntArray()
        for (num in arr) sum += num
        println(sum)
    }
    println("not running anymore")
}

Bonus: Add Safety for Invalid Numbers

If there's a chance your input might include non-numeric values (not just extra spaces), use toIntOrNull() to handle those gracefully instead of crashing:

fun main(args: Array<String>) {
    println("I'm running")
    val str = readLine()
    var sum = 0
    str?.let { input ->
        input.split("\\s+".toRegex())
            .mapNotNull { it.toIntOrNull() } // Only keep valid integers
            .forEach { sum += it }
        println(sum)
    }
    println("not running anymore")
}

This way, even if a non-number slips into your input, the program will just skip it instead of throwing an exception.

Testing with Your Input

Using any of these fixes with your provided input:

56 -44 -72 -79 -38 -80 4 -85 34 -56 -92 51 36 -12 59 -43 31 17 -76 -8 -52 28 45 -68 -96 -7 -70 20

You'll get the correct sum without any crashes.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:08:25