今天的内容是函数的参数和返回值,首先我们继续上一期的程序,写一个fishFood方法:
fun fishFood(day:String):String{
var food = "fasting"
when(day){
"Monday"->food="flakes"
"Tuesday"->food = "pellets"
"Wednesday"->food = "redworms"
"Thursday"->food = "granules"
"Friday"->food = "mosquitoes"
"Saturday"->food = "lettuce"
"Sunday"->food = "plankton"
}
return food
}
函数需要一个String类型的参数day,同时,返回值的类型是String
这里需要注意:
和其他语言不同,我们不需要在when语句中使用break,当执行完一个选择时,其余的便不再执行,可以理解为自动break
kotlin中的任何东西都有一个值,when语句的value值为我们在分支中选择的表达式,所以我们可以优化一下这个函数:
fun fishFood(day:String):String{
return when(day){
"Monday"->"flakes"
"Tuesday"->"pellets"
"Wednesday"->"redworms"
"Thursday"->"granules"
"Friday"->"mosquitoes"
"Saturday"->"lettuce"
"Sunday"->"plankton"
else->"fasting"
}
}
接下来就是本期视频的练习题了:
Use the code you created in the last practice, or copy the starter code from below.
The getFortune() function should really only be getting the fortune, and not be in the business of getting the birthday.
Change your Fortune Cookie program as follows:
Create a function called getBirthday() that gets the birthday from the user.
Pass the result of getBirthday() to getFortune() using an Integer argument, and use it to return the correct fortune.
Remove getting the birthday from getFortune()
Instead of calculating the fortune based on the birthday, use a when statement to assign some fortunes as follows (or use your own conditions):
If the birthday is 28 or 31...
If the birthday is in the first week…
else … return the calculated fortune as before.
Hint: There are several ways in which to make this when statement. How much can you Kotlinize it?
正确答案是:
fun getBirthday(): Int {
print("\nEnter your birthday: ")
return readLine()?.toIntOrNull() ?: 1
}
fun getFortune(birthday: Int): String {
val fortunes = listOf("You will have a great day!",
"Things will go well for you today.",
"Enjoy a wonderful day of success.",
"Be humble and all will turn out well.",
"Today is a good day for exercising restraint.",
"Take it easy and enjoy life!",
"Treasure your friends, because they are your greatest fortune.")
val index = when (birthday) {
in 1..7 -> 4
28, 31 -> 2
else -> birthday.rem(fortunes.size)
}
return fortunes[index]
}