Control Flow
Flag Loops
Use a boolean flag to stop a loop early.
Flag Loops
FlagLoop.scala
object Main {
def main(args: Array[String]): Unit = {
val target =
var current = 1
var checks = 0
var found = false
while (current <= 4 && !found) {
checks = checks + 1
if (current == target) {
found = true
} else {
current = current + 1
}
}
val status = if (found) "found" else "missing"
println("target=" + target)
println("checks=" + checks)
println("status=" + status)
}
}
object Main {
def main(args: Array[String]): Unit = {
val target =
var current = 1
var checks = 0
var found = false
while (current <= 4 && !found) {
checks = checks + 1
if (current == target) {
found = true
} else {
current = current + 1
}
}
val status = if (found) "found" else "missing"
println("target=" + target)
println("checks=" + checks)
println("status=" + status)
}
}
flag-loop
A boolean flag can record when a search is finished. The loop condition can then stop without using a special break statement.