作為 Codegym 大學課程一部分的導師授課片段。報名參加完整課程。


“你好。”

“嗨,艾莉!”

“是時候了解循環了。循環就像 if/else 語句一樣簡單,但更有趣。您可以使用循環多次執行任何命令或命令塊。通常,循環如下所示:”

循環(示例 1)
while(boolean condition)
    command;
循環(示例 2)
while(boolean condition)
    block of commands in curly brackets

“這一切都非常簡單。只要循環條件為真,就會一次又一次地執行命令或塊。首先檢查條件。如果條件為真,則執行循環體(命令塊)。條件再次檢查。如果條件為真,則再次執行循環體。如此重複,直到條件不再為真。”

“如果它始終為真或始終為假怎麼辦?”

“如果它始終為真,那麼程序將永遠不會停止運行:它將無限期地重複循環。如果它始終為假,那麼循環體將永遠不會被執行。”

這裡有些例子:

Java代碼 描述
int i = 3;
while (i >= 0)
{
    System.out.println(i);
    i--;    //Decrease by 1
}
3
2
1
0
int i = 0;
while (i < 3)
{
    System.out.println(i);
    i++;   //Increase by 1
}
0
1
2
boolean isExit = false;
while (!isExit)
{
    String s = buffer.readLine();
    isExit = s.equals("exit");
}
該程序將從鍵盤打印字符串,直到輸入字符串“exit” 。
while (true)
    System.out.println("C");
該程序將在屏幕上重複顯示字母C。
while (true)
{
    String s = buffer.readLine();
    if (s.equals("exit"))
        break;
}
該程序將從鍵盤讀取字符串,直到輸入字符串“exit” 。
2
任務
Java Syntax,  等級 4課堂 8
上鎖
Code entry
Your attention, please! Now recruiting code entry personnel for CodeGym. So turn up your focus, let your fingers relax, read the code, and then... type it into the appropriate box. Code entry is far from a useless exercise, though it might seem so at first glance: it allows a beginner to get used to and remember syntax (modern IDEs seldom make this possible).

“加上條件語句,這個好像也不復雜,我已經想試試了。”