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 chars. 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:

  1. read file string
  2. split string on commas
  3. convert each of result strings int
  4. 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

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -