Kotlin控制台输入处理报错:NumberFormatException异常求助
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 withtoInt(), it throws theNumberFormatExceptionyou'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

