问题
I'm trying to parse 100 50-digit numbers from string with below piece of code:
val input = """37107287533902102798797998220837590246510135740250
|46376937677490009712648124896970078050417018260538
|74324986199524741059474233309513058123726617309629""".stripMargin
val list = input.split("""\n""").map(BigInt(_))
but I'm ending with "java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)". I don't have any idea why this does not work, since when string is splited, each element of list is of type String. Any help would be much appreciated.
Best regards
回答1:
Probably you're on Windows, where the EOL is \r\n.
You've got to strip that, too.
Here, I rebooted into Windows to demo...
apm@halyard ~/tmp
$ vi bigbomb.scala
apm@halyard ~/tmp
$ skalac bigbomb.scala ; skala bigbomb.Test
"ava.lang.NumberFormatException: For input string: "35740250
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
Note that in cygwin, I have to :se fileformat=dos
in vi to use the \r\n line endings.
Here is an example where the unacknowledged impedance mismatch between the source EOL and the runtime EOL bugged me:
some dumb code
You want to use s.lines.mkString
to strip it out.
来源:https://stackoverflow.com/questions/17090537/scala-converting-multiline-string-to-bigint