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

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:

主站蜘蛛池模板: 视频| 鹤壁市| 延吉市| 普洱| 杭锦旗| 七台河市| 瓦房店市| 望都县| 乾安县| 即墨市| 宁乡县| 南通市| 五台县| 新源县| 利辛县| 密云县| 宁晋县| 建宁县| 辽源市| 云梦县| 应用必备| 连平县| 宁安市| 尖扎县| 湖南省| 天气| 恩施市| 大厂| 双城市| 苍溪县| 兴海县| 墨玉县| 绥江县| 潮安县| 蓬安县| 元谋县| 府谷县| 斗六市| 买车| 乌拉特后旗| 房山区|