break
1 Double loop break outer loop
loopOne@ for (i in 1..10) {
println("i ${i}")
for (j in 1..10) {
if (i == 2 && j == 8) break@loopOne
print("j ${j} ")
}
println()
}
The output log is as follows:
2 Double loop break inner loop
for (i in 1..10) {
println("i ${i}")
loopTwo@ for (j in 1..10) {
if (i == 2 && j == 8) break@loopTwo
print("j ${j} ")
}
println()
}
The output log is as follows:
It can be seen from the log that when only i==2 && j==8, the loop of j is interrupted by break, and then i == 3 and will continue to loop afterwards
continue
for (i in 1..10) {
println("i ${i}")
for (j in 1..10) {
if (i == 2 && j == 8) continue
print("j ${j} ")
}
println()
}
The output log is as follows:
It can be seen from the log that in this case only i==2 && j==8, it only stops this time, but will continue the subsequent cycle
to sum up:
1 break interrupt all subsequent cycles of the specified loop
2 continue Interrupt the current operation of the loop that meets the condition, and continue after this interruption
3 The code before the break/continue that meets the conditions will be executed, but the code after it will not be executed, as follows:
for (i in 1..100){
//代码位置1
if (i == 6) break/continue
//代码位置2
}
Code position 1 will be executed; code position 2 will not be executed;