1. Before you begin:
In this Kotlin codelab you will create another dice game, Lucky Dice Roll, trying to roll a lucky number. Your program will set a lucky number and roll the dice. You then check the roll against the lucky number and print an appropriate message to the output. To accomplish this, you will learn how to compare values and make different decisions in your Kotlin program.
To help you focus on the programming concepts without having to worry about the user interface of the app, you will use the browser-based Kotlin programming tool and output your results to the console.
What you'll learn
- How to use
if
andelse
statements - How to compare values using operators such as greater than (
>
), less than (<
), and equal to (==
). - How to use
when
statements to choose an option based on a given value. - What the
Boolean
the datatype is and how to use itstrue
andfalse
values for decision-making.
What you'll build
- A Kotlin-based dice game, Lucky Dice Roll, which allows you to specify a lucky number. A player will win if they roll the lucky number.
2. Decision making within your code:
In your Lucky Dice Roller program, the app should handle different cases such as:
- If the dice roll is the lucky number, then display a congratulations message!
- Else if the dice roll is not the lucky number, then display a message to try again.
if
and else
and when
.fun main() {
val num = 5
if (num > 4) {
println("The variable is greater than 4")
}
}
The variable is greater than 4
>
symbol is an operator for comparing two values, whether the first value is greater than the second value, and returning a result of true
or false
. Other common operators are: <
for less than, ==
for equal, >=
for greater or equal, and <=
for less than equal.Boolean data type for true and false values:
- For a program to test whether a condition is met is called "evaluating the condition". The result of evaluating a condition is
true
if it is met, orfalse
if it is not met. Developers also say, "the condition evaluates totrue
" or "the condition evaluates tofalse
". - Conditions can only evaluate to
true
orfalse
. - Just like there is a data type
Int
for integers, andIntRange
for ranges, there is a data type fortrue
andfalse
, calledBoolean
. You will encounterBoolean
type variables later in this course.
fun main() {
val num = 3
if (num > 4) {
println("The variable is greater than 4")
} else {
println("The variable is less than 4")
}
}
The variable is less than 4
Use an else
+ if
combination to add alternative conditions
fun main() {
val num = 4
if (num > 4) {
println("The variable is greater than 4")
} else if (num == 4) {
println("The variable is equal to 4")
} else {
println("The variable is less than 4")
}
}
The variable is equal to 4
3. Create the Lucky Dice Roll game:
Set up your starter code
fun main() {
val myFirstDice = Dice(6)
val diceRoll = myFirstDice.roll()
println("Your ${myFirstDice.numSides} sided dice rolled ${diceRoll}!")
}
class Dice (val numSides: Int) {
fun roll(): Int {
return (1..numSides).random()
}
}
Check if the lucky number has been rolled
Create a lucky number first, and then compare the dice roll with that number.
- In
main()
, delete theprintln()
statement. - In
main()
, add aval
calledluckyNumber
and set it to 4. Your code should look like this.
fun main() {
val myFirstDice = Dice(6)
val rollResult = myFirstDice.roll()
val luckyNumber = 4
}
- Below, add an
if
statement with a condition inside the parentheses()
that checks ifrollResult
is equal (==
) toluckyNumber
. Leave some room between the curly braces{}
so you can add more code.
fun main() {
val myFirstDice = Dice(6)
val rollResult = myFirstDice.roll()
val luckyNumber = 4
if (rollResult == luckyNumber) {
}
}
- Inside the curly braces
{}
, add aprintln
statement to print"You win!"
fun main() {
val myFirstDice = Dice(6)
val rollResult = myFirstDice.roll()
val luckyNumber = 4
if (rollResult == luckyNumber) {
println("You win!")
}
}
You win!
Respond when the lucky number has not been rolled
- Add an
else
statement to print"You didn't win, try again!"
.
fun main() {
val myFirstDice = Dice(6)
val rollResult = myFirstDice.roll()
val luckyNumber = 4
if (rollResult == luckyNumber) {
println("You win!")
} else {
println("You didn't win, try again!")
}
}
- Add
else if
statements to print a different message for each roll. Refer to the format you learned in the previous task, if necessary.
fun main() {
val myFirstDice = Dice(6)
val rollResult = myFirstDice.roll()
val luckyNumber = 4
if (rollResult == luckyNumber) {
println("You win!")
} else if (rollResult == 1) {
println("So sorry! You rolled a 1. Try again!")
} else if (rollResult == 2) {
println("Sadly, you rolled a 2. Try again!")
} else if (rollResult == 3) {
println("Unfortunately, you rolled a 3. Try again!")
} else if (rollResult == 4) {
println("No luck! You rolled a 4. Try again!")
} else if (rollResult == 5) {
println("Don't cry! You rolled a 5. Try again!")
} else {
println("Apologies! you rolled a 6. Try again!")
}
}
Because having multiple else if
cases is very common, Kotlin has a simpler way of writing them.
4. Use a when statement
else if
statements between the success and the final else
. To make these kinds of statements easier to write and read, which helps avoid errors, Kotlin makes available a when
statement.when
statement. when
statements start with the keyword when
, followed by parentheses ()
. Inside the parentheses goes the value to test. This is followed by curly braces {}
for the code to execute for different conditions.- In your program, in
main()
, select the code from the firstif
statement to the curly brace}
that closes the lastelse
statement and delete it.
fun main() {
val myFirstDice = Dice(6)
val rollResult = myFirstDice.roll()
val luckyNumber = 4
}
- In
main()
, below the declaration ofluckyNumber
, create awhen
statement. Because yourwhen
needs to test against the rolled result, putrollResult
in between the parentheses()
. Add curly braces{}
with some extra spacing, as shown below.
fun main() {
val myFirstDice = Dice(6)
val rollResult = myFirstDice.roll()
val luckyNumber = 4
when (rollResult) {
}
}
As before, first test whether rollResult
is the same as the luckyNumber
.
- Inside the curly braces
{}
of thewhen
statement, add a statement that testsrollResult
againstluckyNumber
, and if they are the same, print the winning message. The statement looks like this:
luckyNumber -> println("You win!")
This means:
- You first put the value you are comparing to
rollResult
. That'sluckyNumber
. - Follow that with an arrow (
->
). - Then add the action to perform if there is a match.
rollResult
is luckyNumber
, then print the "You win!"
message."- Use the same pattern to add lines and messages for the possible rolls 1 - 6, as shown below. Your finished
main()
function should look like this.
fun main() {
val myFirstDice = Dice(6)
val rollResult = myFirstDice.roll()
val luckyNumber = 4
when (rollResult) {
luckyNumber -> println("You won!")
1 -> println("So sorry! You rolled a 1. Try again!")
2 -> println("Sadly, you rolled a 2. Try again!")
3 -> println("Unfortunately, you rolled a 3. Try again!")
4 -> println("No luck! You rolled a 4. Try again!")
5 -> println("Don't cry! You rolled a 5. Try again!")
6 -> println("Apologies! you rolled a 6. Try again!")
}
}
5. Solution code
fun main() {
val myFirstDice = Dice(6)
val rollResult = myFirstDice.roll()
val luckyNumber = 4
when (rollResult) {
luckyNumber -> println("You won!")
1 -> println("So sorry! You rolled a 1. Try again!")
2 -> println("Sadly, you rolled a 2. Try again!")
3 -> println("Unfortunately, you rolled a 3. Try again!")
4 -> println("No luck! You rolled a 4. Try again!")
5 -> println("Don't cry! You rolled a 5. Try again!")
6 -> println("Apologies! you rolled a 6. Try again!")
}
}
class Dice(val numSides: Int) {
fun roll(): Int {
return (1..numSides).random()
}
}
6. Summary
- Use an
if
statement to set a condition for executing some instructions. For example, if the user rolls the lucky number, print a winning message. - The
Boolean
data type has values oftrue
andfalse
and can be used for decision making. - Compare values using operators such as greater than (
>
), less than (<
), and equal to (==
). - Use a chain of
else if
statements to set multiple conditions. For example, print a different message for each possible dice roll. - Use an
else
statement at the end of a chain of conditions to catch any cases that may not be covered explicitly. If you cover the cases for 6-sided dice, anelse
statement would catch the 7 and 8 numbers rolled with an 8-sided dice. - Use a
when
statement as a compact form of executing code based on comparing a value.
8. Practice on your own
Do the following:
- Change
myFirstDice
to have 8 sides and run your code. What happens?
Hint: When you increase the number of sides, your when
statement does not cover all the cases anymore, so for uncovered cases, nothing is printed.
- Fix the
when
statement to account for all 8 sides. You can do this by adding cases for the additional numbers. Challenge: Instead of adding a new case for each number, use anelse
statement to catch all cases that are not covered explicitly.
Hint: You can add more cases to cover more sides. That is a good way to do this, if you want a different message for each number that can be rolled. Or, you can use an else
statement and print the same message for all sides greater than the 6 covered by the current code.
- Change
myFirstDice
to have only 4 sides. What happens?
Hint: Changing the number of sides of the dice to less than what is covered by the when
statement has no noticeable effect, since all the cases that can occur are covered.
0 Comments