Scala - do-while迴圈



while迴圈不同,while迴圈在迴圈頂部測試迴圈條件,而do-while迴圈在迴圈底部檢查其條件。do-while迴圈類似於while迴圈,不同之處在於do-while迴圈至少執行一次。

語法

以下是do-while迴圈的語法。

do {
   statement(s);
} 
while( condition );

請注意,條件表示式出現在迴圈的末尾,因此迴圈中的語句會在條件被測試之前執行一次。如果條件為真,則控制流跳轉回do,並且迴圈中的語句再次執行。此過程重複,直到給定條件變為假。

流程圖

Scala do...while loop

嘗試以下示例程式來理解 Scala 程式語言中的迴圈控制語句(while 語句)。

示例

object Demo {
   def main(args: Array[String]) {
      // Local variable declaration:
      var a = 10;

      // do loop execution
      do {
         println( "Value of a: " + a );
         a = a + 1;
      }
      while( a < 20 )
   }
}

將上述程式儲存為Demo.scala。使用以下命令編譯和執行此程式。

命令

\>scalac Demo.scala
\>scala Demo

輸出

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
scala_loop_types.htm
廣告