Scala cycle
Sometimes, we may need to repeatedly perform the same piece of code. Under normal circumstances, the statements are executed sequentially: the first statement in the function executed first, followed by a second statement, and so on.
Programming languages provide various control structures more complex execution paths.
Loops allow us to repeatedly execute a statement or group of statements, the following is a flow chart of most programming languages in the loop:
Type of cycle
Scala language provides the following cycle types. Click on the link to view the details of each type.
Type of cycle | description |
---|---|
while loop | A series of statements to run if the condition is true, will run repeatedly until the condition becomes false. |
do /en. while loop | While a similar statement before the difference is that the loop condition is determined, the first code block is executed the first cycle. |
for loop | To repeat a series of statements until reaching certain conditions are fulfilled, usually after each cycle is completed by increasing the value of the counter to achieve. |
Loop control statements
Loop control statements change the order of execution of your code, through which you can jump code. Scala following loop control statements:
Scala does not support the break or continue statement, but after version 2.8 provides a way to break the cycle, click on the link below for details.
Control statements | description |
---|---|
break statement | Break loop |
Infinite loop
If the condition is always true, then the loop becomes an infinite loop. We can use the while statement to achieve an infinite loop:
object Test { def main(args: Array[String]) { var a = 10; // 无限循环 while( true ){ println( "a 的值为 : " + a ); } } }
After executing the above code execution cycle will go on forever, you can use Ctrl + C key to interrupt the infinite loop.