0

I tried to use the answer of this question to concert a string of items separated by , into list of Int, so I made this code:

fun main(args: Array<String>) {
    val regex = ","
    val lines = "30,21,29, 31, 40, 48, 53, 47, 37, 39, 31, 29, 17, 9, 20, 24, 27, 35, 41, 38, 27, 31, 27, 26, 21, 13, 21, 18, 33, 35, 40, 36, 22, 24, 21, 20, 17, 14, 17, 19, 26, 29, 40, 31, 20, 24, 18, 26, 17, 9, 17, 21, 28, 32, 46, 33, 23, 28, 22, 27, 18, 8, 17, 21, 31, 34, 44, 38, 31, 30, 26, 32"

    val series = lines.split(regex).toList().map{ it.toInt() }.toList<Int>()

    println(series)
}

But it did not work, and I got this error:

Exception in thread "main" java.lang.NumberFormatException: For input string: " 31" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:569) at java.lang.Integer.parseInt(Integer.java:615) at Reading_many_names_from_the_command_lineKt.main(Reading many names from the command line.kt:5)

3 Answers 3

4

When you split on just , you are going to get all of the whitespace as part of your token.

One solution is to trim the strings before converting to Int:

val series: List<Int> = lines.split(regex).map{ it.trim().toInt() }

I've also simplified your expression, you don't need the extra List conversions.

Sign up to request clarification or add additional context in comments.

Comments

2

Splitting the string on , will leave the whitespace untouched. You can trim all the strings after splitting (like the other answers suggest), or you can split the string on "comma followed (or preceded) by any number of whitespace". To do this, you need to change the regex you are splitting on. Like this:

val regex = "\\s*,\\s*".toRegex()
val series = lines.split(regex).map { it.toInt() }

Comments

1
java.lang.NumberFormatException: For input string: " 31"

The error is right in front of you. " 31" is not a valid number. To fix it you can do map{ it.trim().toInt() } instead of map{ it.toInt() }.

After the split() call you get an array of strings. The elements are: "30", "21", "29", " 31", " 40" etc. The first three numbers are fine, after that they have an additional space character. " 31" can't be converted to an Integer.

To remove the empty space you can use the trim() function.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.