John Squirrels
第 41 级
San Francisco

语句

已在 随机的 群组中发布
我们的第一个程序是一个接一个执行的指令序列。没有叉子。这包括显示问候语的 HelloWorld。它包括算术计算。在我们的第一个程序之后,我们学习了如何分支,即如何使程序根据特定条件执行不同的操作。下面是控制中央供暖和空调系统的代码:

if (tempRoom>tempComfort)
    airConditionerOn();
if (tempRoom<tempComfort)
    heaterOn();
采取下一步。在日常生活中,我们经常进行统一的重复动作,例如,削苹果做馅饼。这个迷人的过程可以描述为:
  1. 如果碗里有苹果,那么我们执行步骤1.1到1.4:

    1. 1.1. 拿一个苹果
    2. 1.2. 去皮切成片
    3. 1.3. 把苹果片放在平底锅里的馅饼皮里
    4. 1.4. 返回步骤 1。
while 语句 - 2假设你有十个苹果、两只手和一把刀。在现实生活中,您按照每个苹果的相同算法依次剥整打苹果。但是我们如何让一个程序对每个苹果做一个重复的动作呢?
  • 我们将自己与苹果的数量联系起来,但如果我们没有足够的苹果,那么一些命令将在没有“有效负载”的情况下执行(我们可能会在尝试剥一个不存在的苹果时割伤自己)。
  • 如果苹果的数量多于要剥皮的命令,那么一些苹果将不被剥皮。
  • 这样的代码很难阅读。它有很多重复,很难修改。

循环是允许重复执行操作的语句

Java 的while循环在我们的例子中会很好地工作。此构造将多个操作放入一个简洁易懂的结构中。使用while循环,一个派的苹果切片算法在 Java 中可能看起来像这样:

while (numberOfApplesInBowl > 0) {
    apple = bowl.grabNextApple();
    arrangeInPie(apple.peel().slice());
    numberOfApplesInBow--; // "--" is the decrement operator, which reduces the number of apples by one
}
System.out.println("The apples for the pie have been processed.");

命令语法

while语句的第一个变体是这样的:

while (Boolean expression) {
	// Loop body — the statement(s) that are repeatedly executed
}
以下是执行此代码时发生的情况的分步说明:
  1. 我们计算while关键字后括号中的布尔表达式。
  2. 如果布尔表达式的计算结果为真,则执行循环体中的语句。循环体中的最后一条语句执行完后,进入第1步
  3. 如果布尔表达式的计算结果为假,那么我们跳转到while循环之后的第一条语句。

有前提条件的循环

因为我们总是在执行循环体之前计算布尔表达式(进入循环的条件) ,所以这种形式的while循环通常称为带前提条件的循环。让我们建立一个数字的前十次幂的表:

public static void main(String[] args) {
    int base = 3; // The number that will be exponentiated
    int result = 1; // The result of exponentiation
    int exponent = 1; // The initial exponent
    while (exponent <= 10) { // The condition for entering the loop
        result = result * base;
        System.out.println(base + " raised to the power of " + exponent + " = " + result);
        exponent++;
    }
}
控制台输出:

3 raised to the power of 1 = 3
3 raised to the power of 2 = 9
3 raised to the power of 3 = 27
3 raised to the power of 4 = 81
3 raised to the power of 5 = 243
3 raised to the power of 6 = 729
3 raised to the power of 7 = 2187
3 raised to the power of 8 = 6561
3 raised to the power of 9 = 19683
3 raised to the power of 10 = 59049
Process finished with exit code 0

带后置条件的循环

这是此循环的第二个变体:

do {
    // Loop body — the statement(s) that are repeatedly executed
} while (Boolean expression);
以下是对执行此代码时发生的情况的解释:
  1. 循环体被执行(紧接在do关键字之后)。
  2. 我们计算while关键字后括号中的布尔表达式。
  3. 如果布尔表达式的计算结果为真,那么我们转到步骤 1
  4. 如果布尔表达式的计算结果为假,那么我们跳转到while循环之后的第一条语句。
与前一个循环的两个主要区别是:1) 循环体至少执行一次,以及 2) 在循环体执行后计算布尔表达式。因此,这种while循环称为带后置条件的循环。这次我们将显示一个不超过 10000 的数的幂表:

public static void main(String[] args) {
    int base = 3; // The number that will be exponentiated
    int result = base; // The result of exponentiation
    int exponent = 1; // The initial exponent
    do {
        System.out.println(base + " raised to the power of " + exponent + " = " + result);
        exponent++;
        result = result * base;
    } while (result < 10000); // The condition for exiting the loop
}
控制台输出:

3 raised to the power of 1 = 3
3 raised to the power of 2 = 9
3 raised to the power of 3 = 27
3 raised to the power of 4 = 81
3 raised to the power of 5 = 243
3 raised to the power of 6 = 729
3 raised to the power of 7 = 2187
3 raised to the power of 8 = 6561
Process finished with exit code 0
注意代码的变化。将此与带有前提条件的循环进行比较。

关于使用循环的有趣事实

循环体内的分支语句

有两个语句会影响循环内的执行:break(我们将在下一章中更详细地讨论)和 继续。
  • continue — 跳过当前迭代中循环体的其余部分的执行并跳转到 while 语句的布尔表达式的计算。如果表达式的计算结果为真,则循环继续。
  • break — 立即终止当前迭代的执行并将控制转移到循环后的第一条语句。因此,该语句结束当前循环的执行。我们将在下一篇文章中更详细地讨论它。
回想一下我们的水果示例。如果我们不确定苹果的质量,我们可以使用 continue语句更改代码:

while (numberOfApplesInBowl > 0) {
    apple = bowl.grabNextApple();
    numberOfApplesInBow--; // "--" is the decrement operator, which reduces the number of apples by one
    if (apple.isBad()) { // This method returns true for rotten apples
        apple.throwInGarbage();
        continue; // Continue the loop. Jump to evaluation of numberOfApplesInBowl > 0
    }
    arrangeInPie(apple.peel().slice());
}
continue语句常用于当满足某个 条件需要执行循环体中的语句时。例如,我们可能希望在触发硬件传感器时执行操作(否则,只需继续我们获取传感器读数的循环)或者我们可能希望仅在循环的某些迭代中计算表达式。后一种情况的一个例子可以在我们使用 while 循环来计算平方小于数字个数的自然数的立方之和中看到。使困惑?查看以下代码:

public static void main(String[] args) {
    int sum = 0;  // Total amount
    int i = 0;  // Initial number in the series
    int count = 20;  // Number of numbers
    while (i <= count) {
        i++;  // Get the next number — "i++" is equivalent to "i = i + 1"
        if (i * i <= count)  // If the square of the number is less than
            continue;  // the number of numbers, then we won't calculate the sum
                            // Jump to the next number in the loop
        sum += i * i * i;  // Otherwise, we calculate the sum of the cubes of numbers
    }  // "sum += i * i * i" is notation that is equivalent to "sum = sum + i * i * i"
    System.out.println(sum);  // Print the result
}

无限循环

这些分支语句最常用于无限循环。如果永远不会满足退出循环的布尔条件,我们称循环为无限循环。在代码中,它看起来像这样:

while (true) {
    // Loop body 
}
在这种情况下, break语句可以帮助我们退出循环。这种类型的循环适用于等待在循环体外部确定的外部条件。比如在操作系统或者游戏中(退出循环就是退出游戏)。或者当使用尝试在循环的每次迭代中改进某些结果但基于经过的时间或外部事件(例如跳棋、国际象棋或天气预报)的发生限制迭代次数的算法时。请记住,在正常情况下,无限循环是不可取的。为了演示,让我们回到求幂:

public static void main(String[] args) {
    int base = 3; // The number that will be exponentiated
    int result = 1; // The result of exponentiation
    int exponent = 1; // The initial exponent
    while (true) {
        result = result * base;
        System.out.println(base + " raised to the power of " + exponent + " = " + result);
        exponent++;
        if (exponent > 10)
            break; // Exit the loop
    }
}
控制台输出:

3 raised to the power of 1 = 3
3 raised to the power of 2 = 9
3 raised to the power of 3 = 27
3 raised to the power of 4 = 81
3 raised to the power of 5 = 243
3 raised to the power of 6 = 729
3 raised to the power of 7 = 2187
3 raised to the power of 8 = 6561
3 raised to the power of 9 = 19683
3 raised to the power of 10 = 59049
Process finished with exit code 0

嵌套循环

现在我们来到关于循环的最后一个话题。回想一下那个苹果派(我希望你现在不饿)和我们的苹果削皮循环:
  1. 如果碗里有苹果,那么我们执行步骤1.1到1.4:

    1. 1.1. 拿一个苹果
    2. 1.2. 去皮切成片
    3. 1.3. 把苹果片放在平底锅里的馅饼皮里
    4. 1.4. 返回步骤 1。
让我们更详细地描述切片过程:
  1. 切片数 = 0
  2. 只要切片数 < 12,然后执行步骤 2.1 到 2.3

    1. 2.1. 从苹果上切下另一片
    2. 2.2. 片数++
    3. 2.3. 返回步骤 2
我们会将其添加到我们的馅饼制作算法中:
  1. 如果碗里有苹果,那么我们执行步骤 1.1 到 1.6:

    1. 1.1. 拿一个苹果
    2. 1.2. 去皮
    3. 1.3. 切片数 = 0
    4. 1.4. 只要切片数 < 12,然后执行步骤 1.4.1 到 1.4.3
      1. 1.4.1. 从苹果上切下另一片
      2. 1.4.2. 片数++
      3. 1.4.3. 返回步骤 1.4
    5. 1.5. 把苹果片放在平底锅里的馅饼皮里
    6. 1.6. 返回步骤 1。
现在我们有一个循环中的循环。像这样的结构很常见。作为最后一个示例,让我们构建一张我们在小学时就爱上的乘法表。

 public static void main(String[] args) {
    // Print the second factors in a row
    System.out.println("    2  3  4  5  6  7  8  9"); 
    int i = 2;  // Assign the first factor to the variable
    while (i < 10) {  // First loop: execute as long as the first factor is less than 10
        System.out.print(i + " | ");  // Print the first factor at the beginning of the line
        int j = 2;  // The starting value of the second factor
        while (j < 10) { // Second loop: execute as long as the second factor is less than 10
            int product = i * j;  // Calculate the product of the factors
            if (product < 10)  // If the product is a single digit, then we print two spaces after the product
                System.out.print(product + "  ");
            else  // Otherwise, print the product and one space after it
                System.out.print(product + " ");
            j++;  // Increment the second factor by one
        }  // Go to the beginning of the second loop, i.e. "while (j < 10)"
        System.out.println();  // Move to the next line on the console
        i++;  // Increment the first factor by one
    } // Go to the beginning of the first loop, i.e. "while (i < 10)"
}
控制台输出:

    2  3  4  5  6  7  8  9
2 | 4 6 8 10 12 14 16 18
3 | 6 9 12 15 18 21 24 27
4 | 8 12 16 20 24 28 32 36
5 | 10 15 20 25 30 35 40 45
6 | 12 18 24 30 36 42 48 54
7 | 14 21 28 35 42 49 56 63
8 | 16 24 32 40 48 56 64 72
9 | 18 27 36 45 54 63 72 81
Process finished with exit code 0
循环(特别是 while语句)是软件的基本构建块之一。通过在 CodeGym 上解决任务,您将了解所有不同类型的循环,了解它们的复杂性,并获得使用它们的实用技能。
评论
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION