Scala - do-while 循环

while 循环在循环顶部测试循环条件,而 do-while 循环在循环底部检查其条件。 do-while 循环类似于 while 循环,不同之处在于 do-while 循环保证至少执行一次。


语法

以下是 do-while 循环的语法。

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

请注意,条件表达式出现在循环的末尾,因此循环中的语句在测试条件之前执行一次。 如果条件为真,则控制流跳回执行,循环中的语句再次执行。 重复此过程,直到给定条件变为假。


流程图

Scala do...while 循环

尝试以下示例程序来理解 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 循环语句