Practice Time: whatShouldIDoToday() - version 2
Practice Time
Improve your whatShouldIDoToday()
program with the new knowledge from this segment.
- Add 3 more situations and activities. For example:
mood == "sad" && weather == "rainy" && temperature == 0 -> "stay in bed" temperature > 35 -> "go swimming"
- Create a single-expression function for each condition and then use it in your
when
expression.
Challenge
Instead of passing in the mood, get a mood string from the user.
Hint: The !! operator may come handy.
// File: Main.kt
// Programmer: Engineer Nolverto Urias Obeso
// Creation Date: 06/15/2023
// Email: nolvertou@gmail.com
// Description: Create a program that suggests an activity based on various parameters
// and create compact functions.
fun main() {
println("Hello Kotlin, What should I do today?")
println("mmm...How are you?")
val mood: String ?= readLine()
println("I'm $mood and I'm going to ${whatShouldIDoToday(mood!!)}")
}
/**
* whatShouldIDoToday function suggests an activity based on various parameters:
* @param mood: a required string parameter
* @param weather: a string parameter that defaults to "sunny"
* @param temperature: an Integer parameter that defaults to 24 (Celsius)
*/
fun whatShouldIDoToday(mood: String,
weather: String = "sunny",
temperature: Int = 24): String{
return when{
goToWalk(mood,weather) -> "go for a walk"
goToSleep(mood, weather, temperature) -> "stay in bed"
goToSwim(temperature) -> "go swimming"
else -> "Stay home and read."
}
}
fun goToWalk(mood: String, weather: String) = ((mood == "happy") && (weather == "Sunny"))
fun goToSleep(mood: String, weather: String, temperature: Int) =
((mood == "sad") && (weather == "rainy") && (temperature == 0))
fun goToSwim(temperature: Int) = temperature > 35
Output
Hello Kotlin, What should I do today?
mmm...How are you?
happy
I'm happy and I'm going to Stay home and read.
Process finished with exit code 0
Comments
Post a Comment