3、函數(shù)的參數(shù)和返回值

今天的內(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]
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容