[Create birthday greetings in Kotlin]

Previous: Write your first program with Kotlin

Introduction

Learning Content

  • How to output more complex text from your program.
  • How to do basic math in Kotlin and store the result in a variable for later use.
  • How to create a function to output the same string multiple times.
  • How to create a loop to output a text snippet multiple times.
    build content
  • You'll create a short program that outputs a birthday greeting, a text-based cake graphic, and a banner.
    required conditions
  • A computer with an internet connection and a modern web browser (such as the latest version of Chrome).

Create birthday wishes in Kotlin

set start code

  1. In your browser, open https://developer.android.com/training/kotlinplayground . This will open a browser-based Kotlin programming tool.
  2. fun main()Inside the function , "Hello, world!"replace the text with "Happy Birthday, Rover!".
  3. Below this line of text (still within curly braces), add two more lines of text to output: "You are already 5!"and "5 is the very best age to celebrate!".
    The completed code should look like this.
fun main() {
    
    
    println("Happy Birthday, Rover!")
    println("You are already 5!")
    println("5 is the very best age to celebrate!")
}
  1. to run your code.
  2. Verify that Happy Birthday, Rover! is displayed in the output pane , followed by You are already 5! followed by 5 is the very best age to celebrate!
Happy Birthday, Rover!
You are already 5!
5 is the very best age to celebrate!

Adding a Birthday Cake
Birthday greetings require a birthday-themed graphic. For example, cake graphics. You can add a cake graphic to your birthday greeting by adding a few additional lines of output println()consisting .

Continue down from the solution code above.

  1. Between the two statements in the code that output Happy Birthdayand , add the following lines of output statements as shown below. The output of these statements produces a cake graph. The last statement has no text between the quotes, which outputs a blank line.You are already 5println()println()
    println("   ,,,,,   ")
    println("   |||||   ")
    println(" =========")
    println("@@@@@@@@@@@")
    println("{~@~@~@~@~}")
    println("@@@@@@@@@@@")
    println("")

To help others understand your code, you can add comments before the statement that outputs the cake graphic. If you run the code, the output won't look any different, because the comments are just information for you and the developer to see, not commands to the system. In-code comments begin with // followed by text, as shown below.

  1. Add a comment before the statement that outputs the cake graphic: // Let's print a cake!.
  2. Add a comment before the statement that prints an empty line: // This prints an empty line.

Your code should look like the code below.

fun main() {
    
    
    println("Happy Birthday, Rover!")

    // Let's print a cake!
    println("   ,,,,,   ")
    println("   |||||   ")
    println(" =========")
    println("@@@@@@@@@@@")
    println("{~@~@~@~@~}")
    println("@@@@@@@@@@@")

    // This prints an empty line.
    println("")

    println("You are already 5!")
    println("5 is the very best age to celebrate!")
}

Tip : Note that we have added some whitespace (empty lines) to the code to separate the various parts of the code. This makes the code clearer and easier to read. You can add blank lines wherever you see fit.

  1. Running your code, the output should look like this.
Happy Birthday, Rover!
   ,,,,,   
   |||||   
 =========
@@@@@@@@@@@
{
    
    ~@~@~@~@~}
@@@@@@@@@@@

You are already 5!
5 is the very best age to celebrate!

Create and use variables

Store the Rover's age in a variable

  • In the code you've completed so far, notice how you're repeating the same age number twice.

Instead of repeating the number, you can store it in one location as a variable, just like putting numbers in a basket and giving them names. You can then use this variable name anytime you need that value. And, if the age changes, you only need to change one place in the program. Changing this variable will output the correct age everywhere it is used.

  • In your program, add the following code as the first line of main()the function to create a agevariable named 5 with the value shown below. (This line must precede
    println()the statement.)
val age = 5

This line says:

  • valis a special word used by Kotlin, called a keyword, to indicate that a variable name follows.

  • ageis the name of the variable.

  • =make the value on its left (age) equal to the value on its right. In mathematics, a single equal sign is used to indicate that the values ​​on both sides of the equal sign are equal. Unlike in mathematics, in Kotlin a single equal sign is used to assign the value on the right side of the equal sign to the specified variable on the left side of the equal sign.

A developer would say something like this: This line declares a variable agenamed that is assigned the value 5.

Important note: Variables declared with valthe keyword can only be set once. The value of this variable cannot be changed later in the program.
You can, however, declare mutable variables using varthe keyword , which you'll do later in the codelab.

To use a variable in an output statement, you need to use symbols around the variable to tell the system that what follows is not text but a variable. The system needs to output the value of the variable, not output text. To do this, you need to enclose the variable within braces and precede it with a dollar sign, as in the example below.

${
    
    variable}
  1. In your code, replace the number 5 in the two output statements with agethe variable , as shown below.
  2. Running your code, both greetings should display the same age.
  3. Change the value of a variable to something else. For example, you can display the Rover's age in days instead of years. To do this, multiply the age by 365, ignoring leap years. You can do this calculation at the time of variable creation, as shown below.
val age = 5 * 365
  1. Run your code again and you'll see that the two blessings now show the age in days.
Happy Birthday, Rover!
   ,,,,,   
   |||||   
 =========
@@@@@@@@@@@
{
    
    ~@~@~@~@~}
@@@@@@@@@@@

You are already 1825!
1825 is the very best age to celebrate!
  1. [Optional] Change the text of the output greeting to be more in line with the day-by-day representation. For example, change to something like this:
You are already 1825 days old!
1825 days old is the very best age to celebrate!

Putting Text into Variables
Not only can you put numbers into variables, but you can also put text into variables.

  1. Under ageVariables , add namea variable named for the name of the birthday person and set its value to "Rover".
val name = "Rover"
  1. Replace the name Rover in the birthday greeting with this variable as shown below.
println("Happy Birthday, ${
      
      name}!")

Output statements can contain multiple variables.

  1. Use namethe variable to Roveradd to the greeting containing the age as shown below.
println("You are already ${
      
      age} days old, ${
      
      name}!")

The completed code should look like this.

fun main() {
    
    

    val age = 5 * 365
    val name = "Rover"

    println("Happy Birthday, ${
      
      name}!")

    // Let's print a cake!
    println("   ,,,,,   ")
    println("   |||||   ")
    println(" =========")
    println("@@@@@@@@@@@")
    println("{~@~@~@~@~}")
    println("@@@@@@@@@@@")

    // This prints an empty line.
    println("")

    println("You are already ${
      
      age} days old, ${
      
      name}!")
    println("${
      
      age} days old is the very best age to celebrate!")
}

congratulations! You can now create greetings that contain text and graphics created with symbols, use variables to store numbers and text, and use variables to output text.

Output birthday banner with border

In this task, you'll create a birthday banner, then learn how to simplify that code using techniques of repetition and reuse of code, and see the benefits of doing so.
Create a Simple Birthday Banner

  1. In https://developer.android.com/training/kotlinplayground
    , place your cursor somewhere in your code.
  2. Right-click to open the menu, then select Select All.
  3. Press Backspace or Delete to delete all codes.
  4. Copy and paste the code below into the editor.
fun main() {
    
    
    println("=======================")
    println("Happy Birthday, Jhansi!")
    println("=======================")
}
  1. Run your program and see the banner output in the console.
=======================
Happy Birthday, Jhansi!
=======================

Create the function to output the border
The code you just pasted and run is a function called main() that contains three output statements. When you press the Run button, the function and all code within it will be executed.

Recap
In the previous codelabs, you learned:

  • A function is a part of a program that performs a specific task.
  • The fun keyword is used to mark some code as a function.
  • The fun keyword is followed by the name of the function, the function's optional inputs (that is, parameters, enclosed in parentheses), and curly braces.
  • Code that outputs text should always be enclosed within these curly braces.

Your Kotlin program must always have a main()function . Besides that, you can create and use your own functions. Just as variables help you avoid duplicating work, functions help you avoid writing the same code multiple times. In your code, the output statements at the top and bottom of the banner are exactly the same. So, let's create and use a function to output these bounding boxes.

  1. In the editor, insert a blank line below main()the function , just to give you some room to maneuver. Blank lines are ignored, so you can insert blank lines wherever you want to organize your code.
  2. Create a function. Start with funthe keyword , followed by the name printBorder, a pair of parentheses (), and a pair of curly braces {}, as shown below.
fun printBorder() {
    
    }

A note on function naming:

  • Note that the name of the function printBorder starts with a lowercase verb. Function names almost always start with a lowercase verb, and the name should describe what the function does. For example: print()or here printBorder().
  • Also note that the second word within the name begins with a capital letter. This style is called "camel case" and it makes names more readable. Take two more examples of names, such as drawReallyCoolFancyBorderand printBirthdayMessage.

Note: Naming functions like this is a "coding convention", a consensus among developers about code formatting. All code is in a similar format, making it easier to read and learn from code written by other programmers. If you look at the code written by other Android developers, the format of that code usually follows these conventions.
For more information on how to format your code, you can find all conventions in the official style guide ( https://developer.android.com/kotlin/style-guide ). There are quite a few conventions listed in this guide, but if you'd like to dig deeper, here's a look.

  1. printBorderUse }the closing curly brace of the function on a new line and add a blank line between the two curly braces to give you enough room to add more code. Keeping the }closing makes it easier to see where the function ends.
  2. Inside main()the function , copy the output statement for outputting the border and paste it printBorder()between the curly braces of the function. The completed printBorder()function should look like this.
fun printBorder() {
    
    
    println("=======================")
}

To use or call a function, use the function name in parentheses. Note that this is how you've been println()using ! So, to use printBorderthe function , call it anywhere you want in your code printBorder().

  1. In main()the function , println()replace the line of code that uses to output the border lines with a call to printBorder()the function . The completed code should look like this.
  2. Run your code to make sure everything works as it did before.

Note that if you change your code to make it easier to use or perform better without changing the output, that change is called refactoring.
Repeating Border Patterns
Look at the border lines, which are actually the same symbol repeated over and over again. Therefore, you are not indicating:

"output this string of 23 symbols",

Instead it indicates this:

"Output this 1 symbol 23 times".

In code, you can issue this instruction using repeat()the statement .

  1. In printBorder()the function , use repeat()the statement to output the equal sign 23 times.
  2. Use println()instead print()to avoid outputting a new line after each "=".

code show as below. You now have an instruction that prints an equal sign, and to repeat that instruction 23 times, you need to use repeat()the statement .

fun printBorder() {
    
    
    repeat(23) {
    
    
        print("=")
    }
}
  • repeat()A statement repeatstarts with , followed by (). Such statements are called "loops" because you repeat or loop the same code multiple times. You'll learn other ways to create loops later.

  • ()In parentheses is the number of repetitions,

  • followed by braces{}

  • {}Inside the braces is the code to repeat.

  1. After the closing curly brace } of the statement in printBorder()the function (that is, after the end of the statement for outputting the border line), add a statement to output a newline.repeat()println()

Your code should now look like this.

fun printBorder() {
    
    
    repeat(23) {
    
    
        print("=")
    }
    println()
}

main()With the code in the function unchanged, your entire program should look like this.

fun main() {
    
    
    printBorder()
    println("Happy Birthday, Jhansi!")
    printBorder()
}

fun printBorder() {
    
    
    repeat(23) {
    
    
        print("=")
    }
    println()
}
  1. to run your code. The output should be the same as before, but this time you only need to specify the "=" sign once to create the border!
=======================
Happy Birthday, Jhansi!
=======================

Changing Borders Using Parameters
What if you want to create borders that use different symbols, such as the ones below?

%%%%%%%%%%%%%%%%%%%%%%%

:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

You can define a separate function for each of these different symbols. However, there is a way to do this more efficiently. You can reuse functions you have already written and use them in a more flexible way, making them suitable for many different symbols.

One advantage of functions is that you can provide input to them using parameters. You scratched the surface of this in an earlier codelab when you started learning about main(). In this step, you'll add a parameter to the printBorder() function that will output any border pattern you provide.

  1. On the first line of main(), create a variable named border for the border pattern. This variable will cause the text to be repeated, generating a border.
val border = "%"
  1. Now, pass that bordervariable as an argument printBorder()into both calls to the function. To do this, you need to borderenclose the ()in parentheses , just as you did for the text to be output println()for .

Your main() function should look like the following code.

fun main() {
    
    
    val border = "%"
    printBorder(border)
    println("Happy Birthday, Jhansi!")
    printBorder(border)
}

printBorder()The function will take the value borderof as input and figure out how to output the full border.

  1. to run your code. Your code will not execute, instead you will see an error icon next to the code.
    insert image description here
    Information displayed in the bottom output barinsert image description here

  2. Look at the output panel, error messages are also displayed there.
    As before, the message indicates where the error occurred and gives hints about its possible cause. The important content is as follows: Too many arguments for public fun printBorder(). You called printBorder()the function and passed the bounding box as input. However, printBorder()the function definition does not currently accept any input.

  3. Fix this bug by adding a parameter representing the border to printBorder()the function definition. Look at the first line of code as shown below.

fun printBorder(border: String) {
    
    
    repeat(23) {
    
    
        print("=")
    }
    println()
}
  • Note that the name of the parameter is border.
  • name followed by a colon:
  • and Stringthe word (describe what kind or type of parameter this is).

StringIs a piece of text consisting of characters enclosed in quotation marks. You can think of it like beads are strung together to form a necklace, and characters are arranged to form words and text. Specifying the parameter as Stringhelps the system to force your parameter to be text rather than other types such as numbers.

  1. to run your code. printBorder()The function now accepts bounding boxes Stringas input. main()The code in is called with borderas argument printBorder(border). Your code should run without errors.
  2. Looking at the output of your program in the console, does it still show the same border as before?
=======================
Happy Birthday, Jhansi!
=======================

This is not expected behavior! Because you meant to draw the border with the "%" sign, while the program is still outputting the border with the "=" sign. In the next steps, you investigate why this happened.

  1. In the editor, notice the gray exclamation mark. This icon indicates a warning. Warnings are issues with the code that require attention, but that do not prevent the code from running. (Note, if you don’t have a gray exclamation mark, don’t be confused. There will be corresponding prompts when you use special compilers such as Android Studio or IDEA in the future. Here, you only need to combine the 9th and 10th to know the solution)
    insert image description here
  2. Hovering over the exclamation point displays a message that reads: "Parameter 'border' is never used."This warning explains a problem with the output. You passed the function a new string representing the border, but didn't use that string for the output.
  3. Change printBorder()the function to use borderthe parameter passed in instead of outputting "=". This has the exact same effect as if borderit were a variable defined inside a function.
fun printBorder(border: String) {
    
    
    repeat(23) {
    
    
        print(border)
    }
    println()
}
  1. Run your code again. The output should look like this.
%%%%%%%%%%%%%%%%%%%%%%%
Happy Birthday, Jhansi!
%%%%%%%%%%%%%%%%%%%%%%%

Great, problem fixed! Below is the finished code.

fun main() {
    
    
    val border = "%"
    printBorder(border)
    println("Happy Birthday, Jhansi!")
    printBorder(border)
}

fun printBorder(border: String) {
    
    
    repeat(23) {
    
    
        print(border)
    }
    println()
}

This greatly increases printBorder()the flexibility when using the function without adding too much code. Borders made of different symbols can now be output with a slight change.

  1. [OPTIONAL] How can I output a birthday banner like the one below if I'm only allowed to change one line of code in the main() function?
***********************
Happy Birthday, Jhansi!
***********************
:::::::::::::::::::::::
Happy Birthday, Jhansi!
:::::::::::::::::::::::

Modify the function to take two parameters What
if you want to use other patterns that consist of multiple characters, eg ? "'-._,-'"You cannot repeat this pattern 23 times, or it will be too long. Maybe, you can repeat 4 times. This is done by changing the number of repetitions in the statement printBorder()of the . repeat()However, there is a better way!

You can define a more complex and refined border by:

  • Patterns that need to be repeated (you've already done that)
  • How many times you want the pattern to repeat
    You can create variables for the pattern and the number of repetitions, and pass both pieces of information to printBorder()the function.
  1. In main(), change the border to the "'-._,-'" pattern.
val border = "`-._,-'"
  1. Run the code and notice that the pattern is now too long.
  2. Under the border definition in main(), create a new variable called timesToRepeat for the number of repetitions. Set its value to 4.
val timesToRepeat = 4
  1. main()In , printBorder()add the number of repetitions as the second argument when calling . Separate the two parameters with a comma.
printBorder(border, timesToRepeat)

main()The function should now look like this:

fun main() {
    
    
    val border = "`-._,-'"
    val timesToRepeat = 4
    printBorder(border, timesToRepeat)
    println("Happy Birthday, Jhansi!")
    printBorder(border, timesToRepeat)
}

As before, this code displays an error because printBorder() is called with more parameters than in the printBorder() definition.

  1. Fix printBorder()so that it also accepts repetitions as input. Add a comma after the parameter, followed by another parameter: timesToRepeat: Int.the first line of the function definition now looks like this.
fun printBorder(border: String, timesToRepeat: Int) {
    
    

Please note:

  • A comma is used to separate the two parameters.
  • timesToRepeatis the name of the parameter,
  • followed by a colon :
  • As well as the type Int. , timesToRepeatit is a number, so its type is Int(abbreviation for integer, which means integer) instead of String.
  1. printBorder()Inside , change repeatto use timesToRepeatthe parameter (instead of the number 23). Your printBorder()code should look like this.
fun printBorder(border: String, timesToRepeat: Int) {
    
    
    repeat(timesToRepeat) {
    
    
        print(border)
    }
    println()
}
  1. to run your code. Its output is shown below.
`-._,-'`-._,-'`-._,-'`-._,-'
Happy Birthday, Jhansi!
`-._,-'`-._,-'`-._,-'`-._,-'
  1. To round out this output, insert two spaces at the beginning of the Happy Birthday greeting. At this point, the output should look like this.
`-._,-'`-._,-'`-._,-'`-._,-'
  Happy Birthday, Jhansi!
`-._,-'`-._,-'`-._,-'`-._,-'

Here is your final code:

fun main() {
    
    
    val border = "`-._,-'"
    val timesToRepeat = 4
    printBorder(border, timesToRepeat)
    println("  Happy Birthday, Jhansi!")
    printBorder(border, timesToRepeat)
}

fun printBorder(border: String, timesToRepeat: Int) {
    
    
    repeat(timesToRepeat) {
    
    
        print(border)
    }
    println()
}

congratulations! After learning about functions, parameters, variables, and repeating loops, you've mastered the basic building blocks you'll use in almost any program.

Take a break and move on to the next task below, where you'll create more functions and loops to build a giant cake with the correct number of candles in it with just a few lines of code.

Create a Layered Cake with Candles

In this quest you will upgrade the birthday cake code so that it will always be the correct size and have the correct number of candles inserted according to age.

  • You'll create a total of 3 functions for drawing a multi-tiered cake with candles inserted in it.
  • You'll use repeat() inside another repeat(), creating a "nested loop".
  • The way to build this code can be used to build any program, building the skeleton first and then adding the details. This is called "top-down development".
  • Our instructions for this exercise are not exhaustive, and you can refer to the completed code if you get stuck.

Here is a graphic of the cake you want to "bake":

 ,,,,,,,,,,,,,,,,,,,,,,,,
 ||||||||||||||||||||||||
==========================
@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@

Here are the instructions.
Create main() function

  1. In the editor, reset your code to Hello, world!program .
  2. You can main()remove the parameter for because you won't be using it again.
  3. main()In , create the variable ageand set it to 24.
  4. main()In , create a second variable layersand set it to 5.
  5. main()In , call the function printCakeCandles()and pass in age. This leaves an error because you haven't created the function.
  6. Similarly, the calling function printCakeTop()is also passed in age.
  7. Finally, the function is called printCakeBottom(), passing both ageand layersthe number of layers.
  8. To eliminate the error, //comment out , as shown below. This way, you can write code without triggering errors.
  9. Run the program, there should be no errors, but it also does nothing.

Your main()function should look like the code below.

fun main() {
    
    
    val age = 24
    val layers = 5
    // printCakeCandles(age)
    // printCakeTop(age)
    // printCakeBottom(age, layers)
}

create printCakeTop()

The to output the top of the cake printCakeTop()is a line of equals signs, printBorder()almost identical to the function you created earlier in this codelab.

==========================
  1. main()Add a blank line under the function and create printCakeTop()the function that takes one parameter Intof age.
  2. Inside the function, use repeat()the statement to output an equal sign age+ 2 times. The extra two equal signs keep the candle from falling out of bounds on the sides of the cake.
  3. Finally, output a blank line repeat()after .
  4. main()In , printCakeTop()remove the two //symbols , since the function now exists.
printCakeTop(age)

Below is the completed function.

fun printCakeTop(age: Int) {
    
    
    repeat(age + 2) {
    
    
        print("=")
    }
    println()
}
  1. Run your code to see the output on top of the cake.
    Create printCakeCandles()
    Each candle consists of two symbols: a comma (,) for the flame, and a vertical bar (|) for the body.
    ,

||||||||||||||||||||||||

To do this with one function, two repeat()statements : one for the flame and one for the body.

  1. main()Under Function and printCakeTop()Function, create a new function printCakeCandles()that takes one parameter Intof age.
  2. Inside the function, add an output statement to output a space
  3. Use repeat()the statement to output a comma ,representing flames.
  4. Repeat this output agetimes .
  5. Finally, output a blank line.
  6. Add output statement to output a space to insert candle.
  7. Below, repeat the steps above to create a second repeat()statement that outputs the body as a vertical bar |.
  8. Finally, use println()to output a new line.
  9. main()In , printCakeCandles()remove the two //symbols .
printCakeCandles(age)
  1. Run your code to see the output of the cake topped with candles

solution:

fun printCakeCandles(age: Int) {
    
    
    print(" ")
    repeat(age) {
    
    
        print(",")
    }
    println() // Print an empty line

    print(" ") // Print the inset of the candles on the cake
    repeat(age) {
    
    
        print("|")
    }
    println()
}

create printCakeBottom()

In this function, you are drawing the bottom of the cake with a width age + 2of and a height of the specified number of layers.

@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@
  • That is, your function takes two parameters: one for the width ( age) and one for the height ( layers).
  • To output the bottom of the cake, first repeat the @ sign age + 2times to output a layer. Then, repeat the output layerslayer .

Draw the @ sign age+2 times to create a layer cake bottom

  1. Below the existing function, agecreate layersa function with two parameters and printCakeBottom(), both of type Int.
  2. Within this function, use repeat()the statement to output one layer of @ symbols @( age + 2times). Finally, output a blank line as shown below.
  3. main()In , printCakeBottom()remove the two //symbols .
fun printCakeBottom(age: Int, layers: Int) {
    
    
    repeat(age + 2) {
    
    
        print("@")
    }
    println()
}
 ,,,,,,,,,,,,,,,,,,,,,,,,
 ||||||||||||||||||||||||
==========================
@@@@@@@@@@@@@@@@@@@@@@@@@@

Nested repeat() statements

To output multiple layers of the same cake base, you can say:

For Tier 1, repeat the symbol 12 times: @@@@@@@@@@@@@

For Tier 2, repeat the symbol 12 times: @@@@@@@@@@@@@

For layer 3, repeat the symbol 12 times: @@@@@@@@@@@@@

Alternatively, it is much more concise to issue instructions as follows:

Repeat three layers:

Repeat the symbol 12 times.
@@@@@@@@@@@@

@@@@@@@@@@@@

@@@@@@@@@@@@

You can now use repeat()the statement to make your code more concise. You can place a repeat()statement repeat()inside another statement. This allows you repeat()to create repeat()statements within statements that output symbols a specific number of times and at a specific number of levels.

Use nested repeat() to output cake layers

  1. Add a second repeat()statement . Repeat this cycle layerstimes .
  2. main()In , printCakeBottom()remove only two lines of code from //.
printCakeBottom(age, layers)
  1. Run your code to see the output of the whole cake.

The solution for printCakeBottom().

fun printCakeBottom(age: Int, layers: Int) {
    
    
    repeat(layers) {
    
    
        repeat(age + 2) {
    
    
            print("@")
        }
        println()
    }
}

congratulations! You have completed a fairly complex program that contains several functions and a nested repeatstatement . Your cake will always have the correct number of candles!

The final output of the program should be:

,,,,,,,,,,,,,,,,,,,,,,,,
 ||||||||||||||||||||||||
==========================
@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@

solution code

fun main() {
    
    
    val age = 24
    val layers = 5
    printCakeCandles(age)
    printCakeTop(age)
    printCakeBottom(age, layers)
}

fun printCakeCandles(age: Int) {
    
    
    print (" ")
    repeat(age) {
    
    
          print(",")
    }
    println() // Print an empty line

    print(" ") // Print the inset of the candles on the cake
    repeat(age) {
    
    
        print("|")
    }
    println()
}

fun printCakeTop(age: Int) {
    
    
    repeat(age + 2) {
    
    
        print("=")
    }
    println()
}

fun printCakeBottom(age: Int, layers: Int) {
    
    
    repeat(layers) {
    
    
        repeat(age + 2) {
    
    
            print("@")
        }
        println()
    }
}

Troubleshooting

If browser-based Kotlin programming tools don't execute your code or show unexpected errors unrelated to your code, you can try the following:

  • Use Shift+Reload to reload the page.
  • Wait a while and try again.

Summarize

  • Use ${}to enclose variables and calculations in the text of an output statement. For example: ${age}, where ageis a variable.
  • Create variables with valkeywords and names. Once this value is set, it cannot be changed. Use the equal sign to assign values ​​to variables. Examples of values ​​include text and numbers.
  • Stringis text enclosed in quotes, eg "Hello".
  • Intis a positive or negative integer, such as 0, 23, or -1024.
  • You can pass one or more parameters into a function for use by the function, for example:fun printCakeBottom(age:Int,layers:Int) {}
  • Use repeat() {}the statement to repeat a set of instructions several times. For example, repeat (23) { print("%") }orrepeat (layers) { print("@@@@@@@@@@") }
  • A loop is an instruction used to repeat an instruction multiple times. repeat()statement is an example of a loop.
  • You can nest loops, that is, put loops inside loops. For example, you repeat()can create a repeat()statement inside a statement that outputs the symbol several times and several lines, like you do with the cake layers.

Summary about function parameter usage: To use a function with parameters, you need to do three things:

  • Add parameters and types to the function definition:printBorder(border: String)

  • Use parameters inside a function:println(border)

  • Provide parameters when calling the function:printBorder(border)

Learn more

Here is the official documentation for the Kotlin concepts you've learned in this article.

Next: [Download and install Android Studio]

Guess you like

Origin blog.csdn.net/Jasonhso/article/details/125871356