fun printHello() {
println("Hello World")
}
printHello()
Hello World
在main的函数中,执行播放按钮,会编译执行,结果在下面显示:
fun main(args: Array<String> ){
println("Hello World!")
dayOfWeek()
}
fun dayOfWeek() {
print("What day is it today?")
}
In the body of the dayOfWeek() function, answer the question by printing the current day of the week.
Hints
Calendar.getInstance().get(Calendar.DAY_OF_WEEK)
import java.util.Calendar
fun main(args: Array<String> ){
println("Hello World!")
dayOfWeek()
}
fun dayOfWeek() {
println("What day is it today?")
val dayOfWeek = Calendar.getInstance().get(Calendar.DAY_OF_WEEK)
// print(dayOfWeek)
when(dayOfWeek) {
1 -> println("Monday")
2 -> println("Tuesday")
3 -> println("Wednesday")
4 -> println("Thursday")
5 -> println("Friday")
6 -> println("Saturday")
7 -> println("Sunday")
}
}
fun main(args: Array<String>) {
println("Hello ${args[0]}")
val isUnit = println("This is an expression")
println(isUnit)
val temperature = 10
val isHot = if (temperature > 50) true else false
println(isHot)
val message = "You are ${ if (temperature > 50) "fried" else "safe" } fish"
println(message)
}
Create a main() function that takes an argument representing the time in 24-hour format (values between and including 0 -> 23).
In the main() function, check if the time is before midday (<12), then print “Good morning, Kotlin”; otherwise, print “Good night, Kotlin”.
Remember that all main() function arguments are Strings, so you will have to convert this argument to an Int before you can apply the check.
fun main(args: Array<String>)
{
if( args[0].toInt() < 12) {
println("Good morning,Kotlin")
} else if( args[0].toInt() in 12..24) {
println("Good night,Kotlin")
} else {
println("Error time")
}
println("Good ${if(args[0].toInt() > 12) "night" else "morning"},Kotlin")
}
import java.util.*
fun main(args: Array<String> ){
println("Hello World!")
feedTheFish()
}
fun feedTheFish() {
val day = randomDay()
val food = "pellets"
println("Today is $day and fish eat $food")
}
fun randomDay() : String {
val week = listOf("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday")
return week[Random().nextInt(7)]
}
Create a program with a function that returns a fortune cookie message that you can print.
fun main(args:Array<String>)
{
var fortune = getFortuneCookie()
println("Your fortune is:$fortune")
}
fun getFortuneCookie() : String
{
val fortunesList:Array<String> = arrayOf("You will have a great day!",
"Things will go well for you today.", "Enjoy a wonderful day fo success.",
"Be humble and all will turn out well.", "Today is good day for exercising restraint.",
"Take it easy and enjoy life!", "Treasure your friends because they are your greatest fortune.")
print("enter your birthday:")
var birthday:Int = readLine()?.toIntOrNull()?:1
var fortuneNum:Int = birthday.mod(7)
return fortunesList[fortuneNum];
}
//结果:
//enter your birthday:14
//Your fortune is:You will have a great day!
fun main(args:Array<String>)
{
//var fortuneNum = getFortuneCookie()
//println("Your fortune is:${fortuneNum}")
var fortune: String
for(i in 1..10) {
fortune = getFortuneCookie()
println("Your fortune is: $fortune")
if(fortune.contains("Take it easy")) break
}
}
fun getFortuneCookie() : String
{
val fortunesList:Array<String> = arrayOf("You will have a great day!",
"Things will go well for you today.", "Enjoy a wonderful day fo success.",
"Be humble and all will turn out well.", "Today is good day for exercising restraint.",
"Take it easy and enjoy life!", "Treasure your friends because they are your greatest fortune.")
print("enter your birthday:")
var birthday:Int = readLine()?.toIntOrNull()?:1
var fortuneNum:Int = birthday.rem(fortunesList.size)
return fortunesList[fortuneNum];
}
fun fishFood(day: String) : String {
var food = "fasting"
return 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
}
//可以改成
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?
Starter Code:
fun main(args: Array) {
var fortune: String
for (i in 1…10) {
fortune = getFortune(getBirthday())
println(“\nYour fortune is: $fortune”)
if (fortune.contains(“Take it easy”)) break;
}
}
fun main(args:Array<String>)
{
var fortune: String
for(i in 1..10) {
fortune = getFortune(getBirthday())
println("Your fortune is: $fortune")
if(fortune.contains("Take it easy")) break
}
}
fun getFortune(birthday: Int) : String
{
val fortunesList:Array<String> = arrayOf("You will have a great day!",
"Things will go well for you today.", "Enjoy a wonderful day fo success.",
"Be humble and all will turn out well.", "Today is 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 28..31 -> 3
1,7 -> 2
else -> birthday.rem(fortunesList.size)
}
return fortunesList[index];
}
fun getBirthday(): Int {
print("enter your birthday:")
return readLine()?.toIntOrNull() ?: 1
}
fun swim(speed: String = "fast") {
println("swimming $speed")
}
//调用swim()时,如果没有参数,就是fast
//也可以混合,可以多个参数,可以指定
Exercise: Fit More Fish
Create a function that checks if we can add another fish into a tank that already has fish in it.
How many fish in a tank?
The most widely known rule for stocking a tank is the one-inch-per-fish-per-gallon-of-water rule. However that’s assuming the tank doesn’t have any decorations in it.
Typically, a tank with decorations can contain a total length of fish (in inches) less than or equal to 80% of the tank size (in gallons). A tank without decorations can contain a total length of fish up to 100% of the tank size.
For example:
A 10 gallon tank with decorations can hold up to 8 inches of fish, for example 4 x 2-inch-long fish.
A 20 gallon tank without decorations can hold up to 20 inches of fish, for example 6 x 1-inch-long fish and 2 x 2-inch-long fish.
fitMoreFish function
Create a function that takes these arguments:
tankSize (in gallons)
currentFish (a list of Ints representing the length of each fish currently in the tank)
fishSize (the length of the new fish we want to add to the tank)
hasDecorations (true if the the tank has decorations, false if not)
You can assume that typically a tank has decorations, and that a typical fish is 2 inches long. That means you can set those values as default parameters.
Output
Make sure you test your code against the following calls, and that you get the correct output for each.
canAddFish(10.0, listOf(3,3,3)) —> false
canAddFish(8.0, listOf(2,2,2), hasDecorations = false) —> true
canAddFish(9.0, listOf(1,1,3), 3) —> false
canAddFish(10.0, listOf(), 7, true) —> true
import java.util.*
fun main() {
println(canAddFish(10.0, listOf(3,3,3)))
println(canAddFish(8.0, listOf(2,2,2), hasDecorations = false))
println(canAddFish(9.0, listOf(1,1,3), 3))
println(canAddFish(10.0, listOf(), 7, true))
}
fun canAddFish(tankSize:Double, currentFish:List<Int>, fishSize:Int = 2, hasDecorations:Boolean = true): Boolean
{
return ((tankSize * if(hasDecorations) 0.8 else 1.0 )>= (currentFish.sum() + fishSize))
}
Practice Time
Create a program that suggests an activity based on various parameters.
Start in a new file with a main function.
From main(), create a function, whatShouldIDoToday().
Let the function have three parameters.
mood: a required string parameter
weather: a string parameter that defaults to “sunny”
temperature: an Integer parameter that defaults to 24 (Celsius).
Use a when construct to return some activities based on combinations of conditions. For example:
mood == “happy” && weather == “Sunny” -> “go for a walk”
else -> “Stay home and read.”
Copy/paste your finished function into REPL, and call it with combinations of arguments. For example:
whatShouldIDoToday(“sad”)
> Stay home and read.
fun main()
{
println(whatShouldDoToday("sad"))
}
fun whatShouldDoToday(mood:String, weather: String = "Sunny", temperature:Int=24) : String
{
return if(mood == "happy" && weather == "Sunny") "go for a walk"
else "Stay home and read."
}
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.
Loops
This lesson introduced the while and repeat loops. To practice using them, do the following:
Change your fortune cookie program to use repeat() instead of a for loop. What happens to the break instruction? Using the error message from the compiler, with what you’ve learned so far, can you think of why?
Change your fortune cookie program to use a while loop, which is the better choice when you are looping until a condition is met.
fun main()
{
println(whatShouldDoToday("sad"))
println(whatShouldDoToday("sad", "rainy", 0))
println(whatShouldDoToday(weather = "rainy", temperature = 0))
}
fun getMood() = "sad"
fun whatShouldDoToday(mood:String = getMood(), weather: String = "Sunny", temperature:Int=24) : String
{
return when {
mood == "happy" && weather == "Sunny" -> "go for a walk"
mood == "sad" && weather == "rainy" && temperature == 0 -> "stay in bed"
temperature > 35 -> "go swimming"
else -> "Stay home and read."
}
}
使用循环的练习
fun main(args:Array<String>)
{
var fortune: String = ""
// repeat(10) {
while(!fortune.contains("Take it easy")) {
// for(i in 1..10) {
fortune = getFortune(getBirthday())
println("Your fortune is: $fortune")
// if(fortune.contains("Take it easy")) break
}
}
fun getFortune(birthday: Int) : String
{
val fortunesList:Array<String> = arrayOf("You will have a great day!",
"Things will go well for you today.", "Enjoy a wonderful day fo success.",
"Be humble and all will turn out well.", "Today is 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 28..31 -> 3
1,7 -> 2
else -> birthday.rem(fortunesList.size)
}
return fortunesList[index];
}
fun getBirthday(): Int {
print("enter your birthday:")
return readLine()?.toIntOrNull() ?: 1
}
fun main()
{
val list = listOf("abc", "ghf", "aaa", "tur")
println(list.filter { it[0] == 'a' })
// eagerExample()
// lazilyExample()
lazilyMapExample()
}
fun eagerExample() {
var list = listOf("rock", "pagoda", "plastic", "tur")
val decorations = list.filter { it[0] == 'p' }
println(decorations)
}
fun lazilyExample() {
var list = listOf("rock", "pagoda", "plastic", "tur")
val decorations = list.asSequence().filter { it[0] == 'p' }
println(decorations)
println(decorations.toList())
}
fun lazilyMapExample() {
println("lazilyMapExample")
var list = listOf("rock", "pagoda", "plastic", "tur")
val decorations = list.asSequence().filter { it[0] == 'p' }
val lazyMap = decorations.asSequence().map {
println("map $it")
it
}
println("lazyMap:${lazyMap}")
println("first:${lazyMap.first()}")
println("all:${lazyMap.toList()}")
}
Practice Time
You can do the following filter exercise in REPL.
Create a list of spices, as follows:
val spices = listOf(“curry”, “pepper”, “cayenne”, “ginger”, “red curry”, “green curry”, “red pepper” )
Create a filter that gets all the curries and sorts them by string length.
Hint: After you type the dot (.), IntelliJ will give you a list of functions you can apply.
Filter the list of spices to return all the spices that start with ‘c’ and end in ‘e’. Do it in two different ways.
Take the first three elements of the list and return the ones that start with ‘c’.
Note: We will be able to do a lot more interesting stuff with filters after you learn about classes and Map.
val spices = listOf("curry", "pepper", "cayenne", "ginger", "red curry", "green curry", "red pepper")
println(spices.filter { it[0] == 'c' && it[it.length-1] == 'e' })
println(spices.filter { it[0] == 'c' && it.endsWith('e')})
println(spices.take(3).filter { it.startsWith('c') })
{println("Hello")}()
Hello
val swim = {println("swim\n")}
swim()
swin
var dirty = 4
val waterFilter = {dirty: Int -> dirty/2}
waterFilter(dirty)
res3: kotlin.Int = 2
fun main(args: Array<String> ){
println("Hello World!")
var swimDontRun = {println("swim\n")}
var swimRunDirectly = { println("swim") }()
var swimRunDirectly2 = run { println("swim") }
swimDontRun()
swimRunDirectly
swimRunDirectly2
var dirty = 20
var waterFilter = {dirty:Int -> dirty /2}
println(waterFilter(dirty))
val waterFilter2: (Int) -> Int = {abc : Int -> abc + 2}
val waterFilter3: (Int) -> Int = {abc -> abc + 2 }
val waterFilter4: (Int) -> Int = { whatever -> whatever*2}
println(waterFilter2(dirty))
println(waterFilter3(dirty))
println(waterFilter4(dirty))
}
Practice Time: Lambdas
Create a lambda and assign it to rollDice, which returns a dice roll (number between 1 and 12).
Extend the lambda to take an argument indicating the number of sides of the dice used for the roll.
If you haven’t done so, fix the lambda to return 0 if the number of sides passed in is 0.
Create a new variable, rollDice2, for this same lambda using the function type notation.
val rollDice = { Random().nextInt(12) + 1 }
val rollDice2 = {sides:Int -> Random().nextInt(sides) + 1}
val rollDice3 = {sides:Int -> if(sides == 0) 0 else Random().nextInt(sides) + 1 }
val rollDice4: (Int) -> Int = {sides -> Random().nextInt(sides) + 1}
Practice Time: Extra Questions
Why would you want to use the function type notation instead of just the lambda?
Create a function gamePlay() that takes a roll of the dice as an argument and prints it out.
Pass your rollDice2 function as an argument to gamePlay() to generate a dice roll every time gamePlay() is called
val dice = {sides:Int -> Random().nextInt(sides) + 1}
val rollDice2:(Int) -> Int = {sides:Int -> if(sides == 0) 0 else Random().nextInt(sides) + 1 }
gamePlay(dice, rollDice2)