在Scala中的while循環 (while loop in Scala)
while loop in Scala is used to run a block of code multiple numbers of time. The number of executions is defined by an entry condition. If this condition is TRUE the code will run otherwise it will not run.
Scala中的while循環用于多次運行代碼塊。 執行次數由輸入條件定義。 如果此條件為TRUE,則代碼將運行,否則它將不運行。
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 entry condition that can be any variable or expression, the value evaluated in TRUE if it's positive and FALSE if it's zero.
當程序沒有有關確切執行次數的信息時,使用while循環 。 執行次數由輸入條件定義,該條件可以是任何變量或表達式,如果值為正數則為TRUE,如果值為零則為FALSE。
This loop might not run even once in the life span of code. If the condition is initially FALSE. The flow will not go in to loop in this case.
即使在代碼的生命周期中,此循環也可能不會運行一次。 如果條件最初為FALSE 。 在這種情況下,該流將不會進入循環。
The while loop is also called entry controlled loop because its condition is checked before the execution of the loop's code block.
while循環也稱為條目控制循環,因為在執行循環的代碼塊之前先檢查其條件。
Syntax of while loop:
while循環的語法:
while(condition){
//Code to be executed...
}
Flow chart of while loop:
while循環流程圖:
Example of while loop:
while循環示例:
object MyClass {
def main(args: Array[String]) {
var myVar = 2;
println("This code prints 2's table upto 10")
while(myVar <= 10){
println(myVar)
myVar += 2;
}
}
}
Output
輸出量
This code prints 2's table upto 10
2
4
6
8
10
Code explanation:
代碼說明:
The above code is to explain the usage of while loop in Scala. In this code, we have used a variable named myVar that is used as a counter in while loop. For printing text, to the screen, we are using println method that moves the cursor to the next line after printing. We have used += assignment operator that we have learned previously. The code prints that table of 2 up to 10.
上面的代碼是解釋Scala中while循環的用法。 在這段代碼中,我們使用了一個名為myVar的變量,該變量在while循環中用作計數器。 為了將文本打印到屏幕上,我們使用println方法,該方法在打印后將光標移動到下一行。 我們使用了先前學習的+ =賦值運算符。 該代碼打印2到10的表。
From this section, I am going to give you assignments that you can complete and submit to know your progress.
在本節中,我將為您提供可以完成并提交的作業,以了解您的進度。
Assignment 1 (difficulty - beginner): Print all numbers from 100 - 399 that are divisible by 3. (use while loop and functions.)
作業1(難度-初學者):打印100至399的所有可被3整除的數字(使用while循環和函數)。
Assignment 2 (difficulty - intermediate): Print all number between 541 - 643 that have 3, 5 and 7 as a factor.
分配2(難度-中等):打印541-643之間的所有數字,其中3、5和7為因數。
翻譯自: https://www.includehelp.com/scala/the-while-loop-in-scala.aspx