官术网_书友最值得收藏!

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:

主站蜘蛛池模板: 铁岭县| 肇州县| 淮阳县| 建德市| 浏阳市| 丹棱县| 盐源县| 乌兰县| 弥渡县| 雅江县| 堆龙德庆县| 井冈山市| 信阳市| 晋城| 元朗区| 新津县| 桐庐县| 麟游县| 天长市| 五原县| 郁南县| 大荔县| 泰来县| 潼南县| 抚宁县| 金阳县| 娄烦县| 蒙阴县| 弥渡县| 泾源县| 普兰店市| 西平县| 子长县| 德江县| 万全县| 牡丹江市| 文化| 射阳县| 北流市| 中牟县| 茌平县|