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
广告
© . All rights reserved.