今天的內(nèi)容是函數(shù)的參數(shù)和返回值,首先我們繼續(xù)上一期的程序,寫(xiě)一個(gè)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
}
函數(shù)需要一個(gè)String類型的參數(shù)day,同時(shí),返回值的類型是String
這里需要注意:
和其他語(yǔ)言不同,我們不需要在when語(yǔ)句中使用break,當(dāng)執(zhí)行完一個(gè)選擇時(shí),其余的便不再執(zhí)行,可以理解為自動(dòng)break
kotlin中的任何東西都有一個(gè)值,when語(yǔ)句的value值為我們?cè)诜种е羞x擇的表達(dá)式,所以我們可以優(yōu)化一下這個(gè)函數(shù):
fun fishFood(day:String):String{
return when(day){
"Monday"->"flakes"
"Tuesday"->"pellets"
"Wednesday"->"redworms"
"Thursday"->"granules"
"Friday"->"mosquitoes"
"Saturday"->"lettuce"
"Sunday"->"plankton"
else->"fasting"
}
}
接下來(lái)就是本期視頻的練習(xí)題了:
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]
}