Scala中的while循环
在Scala中的while循環(huán) (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循環(huán)用于多次運行代碼塊。 執(zhí)行次數(shù)由輸入條件定義。 如果此條件為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.
當程序沒有有關確切執(zhí)行次數(shù)的信息時,使用while循環(huán) 。 執(zhí)行次數(shù)由輸入條件定義,該條件可以是任何變量或表達式,如果值為正數(shù)則為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.
即使在代碼的生命周期中,此循環(huán)也可能不會運行一次。 如果條件最初為FALSE 。 在這種情況下,該流將不會進入循環(huán)。
The while loop is also called entry controlled loop because its condition is checked before the execution of the loop's code block.
while循環(huán)也稱為條目控制循環(huán),因為在執(zhí)行循環(huán)的代碼塊之前先檢查其條件。
Syntax of while loop:
while循環(huán)的語法:
while(condition){//Code to be executed...}Flow chart of while loop:
while循環(huán)流程圖:
Example of while loop:
while循環(huán)示例:
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 10Code 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循環(huán)的用法。 在這段代碼中,我們使用了一個名為myVar的變量,該變量在while循環(huán)中用作計數(shù)器。 為了將文本打印到屏幕上,我們使用println方法,該方法在打印后將光標移動到下一行。 我們使用了先前學習的+ =賦值運算符。 該代碼打印2到10的表。
From this section, I am going to give you assignments that you can complete and submit to know your progress.
在本節(jié)中,我將為您提供可以完成并提交的作業(yè),以了解您的進度。
Assignment 1 (difficulty - beginner): Print all numbers from 100 - 399 that are divisible by 3. (use while loop and functions.)
作業(yè)1(難度-初學者):打印100至399的所有可被3整除的數(shù)字(使用while循環(huán)和函數(shù))。
Assignment 2 (difficulty - intermediate): Print all number between 541 - 643 that have 3, 5 and 7 as a factor.
分配2(難度-中等):打印541-643之間的所有數(shù)字,其中3、5和7為因數(shù)。
翻譯自: https://www.includehelp.com/scala/the-while-loop-in-scala.aspx
總結
以上是生活随笔為你收集整理的Scala中的while循环的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 极米投影仪好用吗?都谁买过能说一下嘛
- 下一篇: 工作排序问题