今天的课程主要将怎样在Kotlin中使用随机数:
首先复习一下上一期的内容,写一个函数:
fun feedTheFish(){
val day = "Tuesday"
val food = "pellets"
println("Today is $day and the fish eat $food")
}
之后再写一个:
fun randomDay():String{
val week = listOf("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday")
return week[Random().nextInt(7)]
}
其中,Random().nextInt(7)生成一个从0到6(不包含7)的随机数字
接下来又是练习题:
- Create a main() function.
- From the main() function, call a function, getFortuneCookie(), that returns a String.
- Create a getFortuneCookie() function that takes no arguments and returns a String.
- In the body of getFortuneCookie(), create a list of fortunes. Here are some ideas:
"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." - Below the list, print: "Enter your birthday: "
Hint: Use print(), not println() - Create a variable, birthday.
- Read the user's input form the standard input and assign it to birthday. If there is no valid input, set birthday to 1.
Hint: Use readLine() to read a line of input (completed with Enter) as a String.
Hint: In Kotlin, you can use toIntOrNull() to convert a number as a String to an Integer numeric. If the user enters "", toIntOrNull returns null.
Hint: Check for null using the ? operator and use the ?: operator to handle the null case. - Divide the birthday by the number of fortunes, and use the remainder as the index for the fortune to return.
- Return the fortune.
- In main(), print: "Your fortune is: ", followed by the fortune string.
还有额外练习:
Use a for loop to run the program 10 times, or until the "Take it easy" fortune has been selected.
标准答案是:
fun main(args: Array<String>) {
println("\nYour fortune is: ${getFortune()}")
}
fun getFortune() : 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.")
print("\nEnter your birthday: ")
val birthday = readLine()?.toIntOrNull() ?: 1
return fortunes[birthday.rem(fortunes.size)]
}
扩展练习的答案是:
fun main(args: Array<String>) {
var fortune: String
for (i in 1..10) {
fortune = getFortune()
println("\nYour fortune is: $fortune")
if (fortune.contains("Take it easy")) break
}
}
网友评论