做...在Scala循环 (do...while loop in Scala)
do...while loop in Scala is used to run a block of code multiple numbers of time. The number of executions is defined by an exit condition. If this condition is TRUE the code will run otherwise it runs the first time only
Scala中的do ... while循环用于多次运行代码块。 执行次数由退出条件定义。 如果此条件为TRUE,则代码将运行,否则它将仅在第一次运行
The do...while loop is used when the program does not have information about the exact number of executions taking place. The number of executions is defined by an exit condition that can be any variable or expression, the value evaluated in TRUE if it's positive and FALSE if it's zero.
当程序没有有关发生的确切执行次数的信息时,使用do ... while循环 。 执行次数由退出条件定义,退出条件可以是任何变量或表达式,如果值为正数则为TRUE,如果为零则为FALSE 。
This loop always runs once in the life span of code. If the condition is initially FALSE. The loop will run once in this case.
该循环在代码的生命周期中始终运行一次。 如果条件最初为FALSE 。 在这种情况下,循环将运行一次。
The do...while loop is also called exit controlled loop because its condition is checked after the execution of the loop's code block.
do ... while循环也称为退出控制循环,因为在执行循环的代码块后会检查其条件。
Syntax of do...while loop:
do ... while循环的语法:
do{
//Code to be executed...
}
while(condition);
Flow chart of do...while loop:
do ... while循环流程图:
Example of do...while loop:
do ... while循环的示例:
object MyClass {
def main(args: Array[String]) {
var myVar = 12;
println("This code prints myVar even if it is greater that 10")
do{
println(myVar)
myVar += 2;
}
while(myVar <= 10)
}
}
Output
输出量
This code prints myVar even if it is greater that 10
12
Code explanation:
代码说明:
This code implements the use of the do...while loop in Scala. The do...while loop being an exit control loop checks the condition after the first run. This is why the code prints 12 but the condition is myVar should not be greater than 10. In this we put the condition after the code block this means the code will run like this, print myVar increment it by 2 (using assignment operator) and then checks for the condition of the loop.
这段代码实现了Scala中do ... while循环的使用。 作为退出控制循环的do ... while循环在第一次运行后检查条件。 这就是为什么代码打印12但条件为myVar不应大于10的原因。在此,我们将条件放在代码块之后,这意味着代码将像这样运行,打印myVar将其递增2(使用赋值运算符 ),然后检查循环条件。
The assignments for the do...while loop that you can complete and submit to know your progress.
您可以完成并提交do ... while循环的作业,以了解自己的进度。
Assignment 1 (difficulty - beginner): Print all prime numbers from 342 - 422 that is divisible by 3. (use do-while loop and functions.)
作业1(难度-初学者):打印342-422中所有可被3整除的质数。(使用do-while循环和函数。)
Assignment 2 (difficulty - intermediate): Print all number between 54 - 1145 that have 11,13 and 17 as a factor.
作业2(难度-中间):打印54-1145之间的所有数字,其中11、13和17为因数。
翻译自: https://www.includehelp.com/scala/the-do-while-loop-in-scala.aspx