0
0
Kotlinprogramming~30 mins

Labeled break and continue in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Labeled break and continue in Kotlin
📖 Scenario: Imagine you are organizing a small sports event. You have a list of teams and their players. You want to find the first team that has a player named "Alex" and stop searching once you find it. Also, you want to skip any team that has no players.
🎯 Goal: You will write a Kotlin program that uses labeled break and continue statements to efficiently search through teams and players.
📋 What You'll Learn
Create a map called teams with exactly these entries: "Tigers" with players ["John", "Alex", "Sam"], "Lions" with players [], and "Bears" with players ["Mike", "Anna"].
Create a Boolean variable called foundAlex and set it to false.
Use a labeled for loop named teamLoop to iterate over teams. Inside, skip teams with no players using a labeled continue. If a player named "Alex" is found, set foundAlex to true and use a labeled break to exit the outer loop.
Print "Found Alex in team: <teamName>" if foundAlex is true, otherwise print "Alex not found in any team".
💡 Why This Matters
🌍 Real World
Using labeled break and continue helps when searching through complex data like teams and players, allowing you to stop or skip parts efficiently.
💼 Career
Understanding labeled loops is useful in software development when working with nested data structures or complex loops, improving code clarity and performance.
Progress0 / 4 steps
1
Create the teams map
Create a map called teams with these exact entries: "Tigers" with players ["John", "Alex", "Sam"], "Lions" with players [], and "Bears" with players ["Mike", "Anna"].
Kotlin
Need a hint?

Use mapOf to create the map. Each team name maps to a list of player names.

2
Create the foundAlex variable
Create a Boolean variable called foundAlex and set it to false.
Kotlin
Need a hint?

Use var to create a variable that can change later.

3
Use labeled loops with break and continue
Use a labeled for loop named teamLoop to iterate over teams. Inside, skip teams with no players using a labeled continue. If a player named "Alex" is found, set foundAlex to true and use a labeled break to exit the outer loop.
Kotlin
Need a hint?

Label the outer loop with teamLoop@. Use continue@teamLoop to skip empty teams. Use break@teamLoop to stop searching when "Alex" is found.

4
Print the result
Print "Found Alex in team: <teamName>" if foundAlex is true, otherwise print "Alex not found in any team". Use the variable teamName from the loop where foundAlex was set.
Kotlin
Need a hint?

Remember to store the team name when you find Alex, so you can print it after the loops.