Sum of n numbers result is wrong in Scala -
i reading comma-separated numbers text file , performing addition of numbers in file - sum i'm getting wrong.
input file
1,2,3
source code
val file=source.fromfile("d:/scala/test.txt") val f1=file.foldleft(0)((a,b)=>a+b) println(f1)
output
238
i can perform addition on array , works fine, can't correct answer when reading data file.
a source
iterator[char]
, foldleft
operating on char
s. when add 2 chars +
, you're adding decimal values.
your source reading every character file, including commas. if @ ascii chart, you'll see decimal value of comma (i.e. ,
) 44, , 1, 2, , 3 49, 50 , 51 respectively.
this gives 44 + 44 + 49 + 50 + 51 = 238
, result you're seeing.
what want this:
- read file string
- split string on commas
- convert each of result strings int
- sum resulting integers
which can written as
source.fromfile("d:/scala/test.txt").mkstring.split(',').map(_.toint).sum
or
source.fromfile("d:/scala/test.txt").mkstring.split(',').map(_.trim.toint).sum
note toint
throw if input can't parsed int.
Comments
Post a Comment