Kotlin \ Java - How to get the sum of the changed elements of an array

I have a range of prices that are strings and look like "$ 100.00". I want to check the sum of all these prices, but before I need to change the row to a number, I did it like this:

val price2 = "$100.00"
val price3 = "INCLUDED"
val price4 = "$200.00"
val prices: Array<String> = arrayOf(price2, price3, price4)

      

This is how I change String to Float:

 for (s: String in prices) {
            //I replace all dollar signs to empty space
            val s1 = s.replace("$", "")
            //I replace Included price to 0
            val s2 = s1.replace("INCLUDED", "0")
            //Change type to float
            val p = s2.toFloat()
            println(p)
        }

      

How do you find the sum of all these changed items? I mean, I need a sum of 100.0 + 0.0 + 200.0. Things I've tried:

//added this into for loop  
val sum = +p
println(sum)

      

or

 //I tried to put this into the loop and after it
 val x = prices[0] + prices[1] + prices[2]
 println(x)

      

Thanks for any help! I tried to write in Kotlin, but Java examples will be fine.

EDIT: I was thinking of adding p to a new array and then finding the sum of the second array, but I don't know how.

+3


source to share


3 answers


A simpler solution:



val prices = listOf(price2, price3, price4)
val pricesParsed = prices.map {it.replace("$", "")}.map {it.toFloatOrNull() ?: 0f}
println(pricesParsed.sum())

      

+2


source


Try the following:



var sum = 0
for (s: String in prices) {
        //I replace all dollar signs to empty space
        val s1 = s.replace("$", "")
        //I replace Included price to 0
        val s2 = s1.replace("INCLUDED", "0")
        //Change type to float
        val p = s2.toFloat()
        println(p)
        sum += p // NO var keyword!
}
println(sum)

      

+3


source


You can go with this too:

var p:Float = 0.0f
for(i :String in prices) {
   var s1 =   i.replace("$","")
   var s2 = s1.replace("INCLUDED","0")
   p  = p + s2.toFloat()
}

      

+1


source







All Articles