- Kotlin Programming By Example
- Iyanu Adelekan
- 350字
- 2021-08-27 20:00:11
The break and continue keywords
Often when declaring loops, there is a need to either break out of the loop if a condition fulfills, or start the next iteration at any point in time within the loop. This can be done with the break and continue keywords. Let's take an example to explain this further. Open a new Kotlin script file and copy the following code into it:
data class Student(val name: String, val age: Int, val school: String)
val prospectiveStudents: ArrayList<Student> = ArrayList()
val admittedStudents: ArrayList<Student> = ArrayList()
prospectiveStudents.add(Student("Daniel Martinez", 12, "Hogwarts"))
prospectiveStudents.add(Student("Jane Systrom", 22, "Harvard"))
prospectiveStudents.add(Student("Matthew Johnson", 22, "University of Maryland"))
prospectiveStudents.add(Student("Jide Sowade", 18, "University of Ibadan"))
prospectiveStudents.add(Student("Tom Hanks", 25, "Howard University"))
for (student in prospectiveStudents) {
if (student.age < 16) {
continue
}
admittedStudents.add(student)
if (admittedStudents.size >= 3) {
break
}
}
println(admittedStudents)
The preceding program is simplistic software for selecting admitted students out of a list of prospective students. We create a data class at the start of our program to model the data of each student, then two array lists are created. One array list holds the information of the prospective students, those that have applied for admission, and the other list holds the information of the students that have been admitted.
The next five lines of code add prospective students to the prospective student list. We then declare a loop that iterates over all students present in the prospective student list. If the age of the current student in the loop is less than 16 years old, the loop skips to the next iteration. This models the scenario in where a student is too young to be admitted (thus not added to the admitted students list).
If the student is 16 or older, the student is added to the admitted list. An if expression is then used to check whether the number of admitted students is greater than or equal to three. If the condition is true, the program breaks out of the loop and no further iterations are done. The last line of the program prints out the students present in the list.
Run the program to see the output:

- Vue.js設計與實現
- Spring 5企業級開發實戰
- 表哥的Access入門:以Excel視角快速學習數據庫開發(第2版)
- Mastering Python Design Patterns
- UML2面向對象分析與設計(第2版)
- Zabbix Performance Tuning
- Elasticsearch Essentials
- Arduino Wearable Projects
- 金融商業數據分析:基于Python和SAS
- Node.js應用開發
- JavaScript編程精解(原書第3版)
- Python深度學習:基于PyTorch
- Node.js核心技術教程
- 數據庫基礎與應用實驗教程:Visual FoxPro 6.0
- OpenCV:Computer Vision Projects with Python