Scala do...while Loop

Scala 循环Scala Loops

Unlike the while loop, which tests the loop condition at the top of the loop, in Scala, the do...while loop checks its condition at the bottom of the loop.

The do...while loop is similar to the while loop, but the do...while loop ensures that the loop is executed at least once.


Syntax

In the Scala languagewhileThe syntax of the loop is:

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

Flowchart

Scala 中的 do...while 循环

Please note that the condition expression appears at the bottom of the loop, so the statement(s) in the loop are executed at least once before the condition is tested.

If the condition is true, the control flow jumps back to the do above, and the statement(s) in the loop are executed again.

This process repeats until the given condition becomes false.

Example

Example

object Test {
   def main(args: Array[String]) {
      // local variable
      var a = 10;

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

Executing the above code produces the following output:

$ 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

Scala 循环Scala Loops

Other Extensions