Scala do…while 循環
不像while 循環在循環頭部測試循環條件, Scala 語言中,do...while 循環是在循環的尾部檢查它的條件。
do...while 循環與while 循環類似,但是do...while 循環會確保至少執行一次循環。
語法
Scala語言中while循環的語法:
do { statement(s); } while( condition );
流程圖
請注意,條件表達式出現在循環的尾部,所以循環中的statement(s) 會在條件被測試之前至少執行一次。
如果條件為true,控制流會跳轉回上面的do,然後重新執行循環中的statement(s)。
這個過程會不斷重複,直到給定條件變為false 為止。
實例
object Test { def main(args: Array[String]) { // 局部变量 var a = 10; // do 循环 do{ println( "Value of a: " + a ); a = a + 1; }while( a < 20 ) } }
執行以上代碼輸出結果為:
$ scalac Test.scala $ scala Test value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 15 value of a: 16 value of a: 17 value of a: 18 value of a: 19