Add conditional behavior in Kotlin

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 and else 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 its true and false 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:

Your Lucky Dice Roller program needs to determine whether the user has rolled a lucky number and gets congratulations, or instead, gets a message to try again.

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.
To add this logic to your code, use special Kotlin keywords such as 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
Recap: The > 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, or false if it is not met. Developers also say, "the condition evaluates to true" or "the condition evaluates to false".
  • Conditions can only evaluate to true or false.
  • Just like there is a data type Int for integers, and IntRange for ranges, there is a data type for true and false, called Boolean. You will encounter Boolean 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:

In this section, using what you learned in the previous task, you will update the Dice Roller program to check whether you have rolled a preset lucky number. If you have, you win!

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.

  1. In main(), delete the println() statement.
  2. In main(), add a val called luckyNumber and set it to 4. Your code should look like this.
fun main() {
    val myFirstDice
= Dice(6)
    val rollResult
= myFirstDice.roll()
    val luckyNumber
= 4
}
  1. Below, add an if statement with a condition inside the parentheses () that checks if rollResult is equal (==) to luckyNumber. 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) {

   
}
}
  1. Inside the curly braces {}, add a println 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

  1. 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

Testing for many different outcomes, or cases, is very common in programming.
Sometimes, the list of possible outcomes can be very long. For example, if you were rolling 12-sided dice, you'd have 11 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.
You are going to change your program to use a 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.
  1. In your program, in main(), select the code from the first if statement to the curly brace } that closes the last else statement and delete it.
fun main() {
    val myFirstDice
= Dice(6)
    val rollResult
= myFirstDice.roll()
    val luckyNumber
= 4
}
  1. In main(), below the declaration of luckyNumber, create a when statement. Because your when needs to test against the rolled result, put rollResult 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.

  1. Inside the curly braces {} of the when statement, add a statement that tests rollResult against luckyNumber, 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's luckyNumber.
  • Follow that with an arrow (->).
  • Then add the action to perform if there is a match.
Read this as, "If rollResult is luckyNumber, then print the "You win!" message."
  1. 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!")
   
}
}
Congratulations! I have learned two ways of printing messages depending on a condition. This is a powerful tool for writing interesting programs!

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 of true and false 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, an else 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:

  1. 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.

  1. 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 an else 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.

  1. 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

Brand creation, trend analysis & style consulting

Lorem Ipsum has been the industry's standard dummy text ever since. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since.