Kotlin \ Java - 如何获取已更改的数组元素的总和

时间:2017-07-03 03:19:15

标签: java kotlin

我有一系列价格是字符串,看起来像这样" $ 100.00"。 我想检查所有这些价格的总和,但在我需要将String更改为数字之前,我这样做了:

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

这里是我如何将String更改为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)
        }

如何找到所有这些变化元素的总和?我的意思是,我希望总和为100.0 + 0.0 + 200.0。 我试过的事情:

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

或者

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

感谢您的帮助!我一直试图在Kotlin写作,但Java示例会很好。

编辑:我一直在考虑将p添加到新阵列中然后找到第二阵列的总和,但我不知道如何做到这一点。

3 个答案:

答案 0 :(得分:3)

试试这个:

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)

答案 1 :(得分:2)

更实际的解决方案:

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

答案 2 :(得分:1)

也可以这样做:

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