0

Why can't this work for me in Kotlin

fun main(args: Array<String>) { var hours = readLine()!!.toInt() val total: Double=0.0 println($hours) val total: Double =when{ hours<=5->1*hours hours>5&&hours<24->0.5*hours hours==24->15 hours>24->15+0.5*(hours-24) else->0 } println(total) }

9th Feb 2022, 12:28 PM
Solomon Obonyo
Solomon Obonyo - avatar
2 Answers
+ 3
you don't need to declare total twice. using val total means it's not going to be reassigned again. change input to Double to avoid mixing Int and Double. fun main(args: Array<String>) { var hours = readLine()!!.toDouble() //val total: Double=0.0 println(hours) //remove $ var total: Double = when{ hours<=5->1*hours hours>5&&hours<24->0.5*hours hours==24->15.0 //add .0 hours>24->15+0.5*(hours-24) else->0.0 //add .0 } println(total) }
9th Feb 2022, 2:29 PM
Bahha┣
Bahha┣ - avatar
+ 2
Solomon Obonyo 1 - you have declared total twice 2 - if you assign switch case as double then atleast 1 value should be of type double 3 - condition were wrong if hours is more than 48 then rent would be 15 per 24 hour and 0.5 each hours so condition should be like this: 15 * (hours / 24) + 0.5 * (hours % 24) Here is the solution fun main(args: Array<String>) { var hours = readLine()!!.toInt() // val total: Double=0.0 // println($hours) val total: Double = when { hours <= 5 -> 1.0 * hours hours > 5 && hours < 24 -> 5 + 0.5 * (hours - 5) hours == 24 -> 15.0 hours > 24 -> 15 * (hours / 24) + 0.5 * (hours % 24) else -> 0.0 } println(total) }
9th Feb 2022, 2:51 PM
AÍąJ
AÍąJ - avatar