【Scala】迴圈控制 break與continue
阿新 • • 發佈:2019-02-04
最開始Scala在迴圈之中是不把break和continue當做關鍵字的,並且也沒有預設可使用的break和continue,Scala推薦的是運用自定的bool值來控制迴圈,下面為示例
break-跳出所有迴圈
def breakDemo(): Unit = { val l = List.range(1, 10) var breakFlag = false var index = 0 // 只打印小於等於5的數字,如下為三種break的方法 // 運用while while (index < l.length && !breakFlag) { val num = l(index) println(num) index += 1 if (num >= 5) breakFlag = true } println("while done") // 運用for breakFlag = false for (num <- l if !breakFlag) { println(num) if (num >= 5) breakFlag = true } println("for done") // 運用scala.util.control.Breaks,會丟擲一個異常來中斷迴圈 for (num <- l) { println(num) if (num >= 5) scala.util.control.Breaks.break() } println("scala.util.control.Breaks done") }
continue-跳出當前迴圈
def continueDemo(): Unit = { val l = List.range(1, 10) var continueFlag = false var index = 0 // 只打印大於5的數字,如下為三種break的方法 // 運用while while (index < l.length) { val num = l(index) continueFlag = if (num <= 5) { true } else { false } if (!continueFlag) { println(num) } index += 1 } println("while done") // 運用for continueFlag = false for (num <- l) { continueFlag = if (num <= 5) { true } else { false } if (!continueFlag) { println(num) } } println("for done") }