JavaRush /Java 博客 /Random-ZH /Java 中的 While 循环

Java 中的 While 循环

已在 Random-ZH 群组中发布

介绍

我们的第一个程序是一系列依次执行的指令。没有叉子。这是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
假设您有 10 个苹果、两只手和一把刀。在生活中,您会在相同算法的指导下持续清理整个十个。如何让程序对每个苹果执行重复操作?
  • 让我们将自己与苹果的数量绑定起来,但是如果我们的苹果数量很少,那么一些命令将在没有“有效负载”的情况下徒劳地执行(也许我们会在剥一个不存在的苹果时割伤自己)。
  • 如果苹果的数量多于我们的加工团队,那么有些产品将无法加工。
  • 这样的“代码”难以阅读,包含大量重复内容,并且难以修改。

循环是多次执行操作的运算符。

Java while 循环(恶意循环)在我们的例子中运行良好。这种设计将多个动作组织成一个简洁易懂的结构。在 Java 中切片苹果做馅饼的 while 算法可能如下所示:
while(числоЯблокВТазике>0) {
    яблоко = тазик.взятьОчередноеЯблоко();
    положитьВПирог(яблоко.чистить().нарезать());
    числоЯблокВТазике--;//-- this is a decrement, reduces the number of apples by one
}
System.out.println('Apples for the pie are processed.');

命令语法

第一种描述 while 语句的方式如下:
while(Логическое выражение) {
	// Loop body - periodically executed statement(s)
}
这是按如下方式完成的(一步一步):
  1. 我们评估括号中 while 后面的布尔条件。
  2. 如果逻辑条件为真,则执行循环体中的运算符,执行完循环体中的最后一个运算符后,转到步骤1
  3. 如果逻辑条件为 false,则转到 while 循环外的第一个语句。

有前提条件的循环

由于在执行循环体之前,我们总是预先计算一个逻辑表达式(进入循环的条件),因此这种类型的 while 通常称为带前提条件的循环。让我们构建一个包含前十个整数(数字的正幂)的表:
public static void main(String[] args) {
    int number = 3; // Number to be raised to a power
    int result = 1; // Result of exponentiation
    int power = 1; // Initial exponent
    while(power <= 10) { // loop entry condition
        result = result * number;
        System.out.println(number + "to the extent" + power + " = " + result);
        power++;
    }
}
控制台输出结果:
3 в степени 1 = 3
3 в степени 2 = 9
3 в степени 3 = 27
3 в степени 4 = 81
3 в степени 5 = 243
3 в степени 6 = 729
3 в степени 7 = 2187
3 в степени 8 = 6561
3 в степени 9 = 19683
3 в степени 10 = 59049
Process finished with exit code 0

带后置条件的循环

第二种循环:
do {
    // Loop body - periodically executed statement(s)
}while (Логическое выражение);
执行如下(步骤):
  1. 循环体被执行(紧接在 do 关键字之后)。
  2. 我们评估括号中 while 后面的布尔条件。
  3. 如果逻辑条件为真,则转至步骤1
  4. 如果逻辑条件为 false,则转到 while 循环外的第一个语句。
与以前类型的循环有两个主要区别:循环体至少执行一次,并且在执行循环体后检查逻辑条件。因此,这种类型的 while 循环称为后置条件循环。这次我们将显示一个不超过10000的数的幂表:
public static void main(String[] args) {
    int number = 3;// Number to be raised to a power
    int result = number;// Result of exponentiation
    int power = 1;// Initial exponent
    do {
        System.out.println(number + "to the extent" + power + " = " + result);
        power++;
        result = result * number;
    }while (result < 10000); // loop exit condition
控制台输出结果:
3 в степени 1 = 3
3 в степени 2 = 9
3 в степени 3 = 27
3 в степени 4 = 81
3 в степени 5 = 243
3 в степени 6 = 729
3 в степени 7 = 2187
3 в степени 8 = 6561
Process finished with exit code 0
注意代码中的变化,将其与带有前提条件的循环版本进行比较。

有关使用循环的有趣事实

循环体中的控制命令

有两个命令会影响循环的进度:break,我们将在下一章中展示其功能,以及 继续。
  • continue – 停止执行当前循环体并移至 while 运算符的逻辑表达式。如果计算的表达式为真,则循环的执行将继续。
  • Break – 立即停止当前循环的执行并跳转到其外部的第一个命令。因此,当前循环的执行被中断。我们将在下一个主题中更详细地讨论它。
让我们记住我们的水果例子。如果我们不确定所提供的苹果的质量,我们可以使用以下命令更改代码 continue
while(числоЯблокВТазике>0) {
    яблоко = тазик.взятьОчередноеЯблоко();
    числоЯблокВТазике--;//-- this is a decrement, reduces the number of apples by one
    if (яблоко.плохое()) {  // method will return true for rotten, etc. apples
        яблоко.выкинутьВМусор();
        continue; // continue the loop, go to the condition number ofApplesIn the Basin>0
    }
    положитьВПирог(яблоко.чистить().нарезать());
}
continue当在循环体中需要在特定条件发生时执行命令时,通常会使用该结构,例如,在触发设备中的传感器时执行操作(否则只需继续读取其指示器的循环) 或仅在循环的某些步骤计算表达式。最后一种情况的示例是在 while 循环中计算平方小于其数量的自然数的立方和:
public static void main(String[] args) {
    int sum = 0;    // total amount
    int i = 0;      // starting number of the row
    int count = 20; // amount of numbers
    while(i<=count) {
        i++;        // take the next number, i++ is equivalent to i=i+1
        if (i*i<=count)  // if the square of the number is less
            continue;   // number of numbers - do not count the sum
                        // move on to the next number in the loop
        sum += i*i*i; // otherwise, we calculate the sum of cubes of numbers
    } // sum += i*i*i - notation similar to sum = sum + i*i*i
    System.out.println(sum);// print result
}

无限循环

这些控制命令最常在无限循环中使用。之所以这样称呼,是因为逻辑退出条件永远不会得到满足。在代码中它看起来像这样:
while(true) {
    // Loop body
}
break在这种情况下,使用命令来组织退出 将很有用。当等待在循环体逻辑之外形成的外部条件时,会发生这种类型的循环。例如,在模拟英雄周围的虚拟世界的游戏中(退出循环=退出游戏)、操作系统。或者,当使用算法时,也许可以通过循环中的每个后续调用来改进结果,但通过时间或外部事件(跳棋、国际象棋或天气预报)的发生来限制它们。应该记住,在正常情况下,无限循环是程序不稳定的问题之一。为了进行演示,让我们回到数字的幂:
public static void main(String[] args) {
    int number = 3; // Number to be raised to a power
    int result = 1; // Result of exponentiation
    int power = 1; // Initial exponent
    while(true) {
        result = result * number;
        System.out.println(number + "to the extent" + power + " = " + result);
        power++;
        if (power>10)
            break; // exit from the loop
    }
}
控制台输出结果:
3 в степени 1 = 3
3 в степени 2 = 9
3 в степени 3 = 27
3 в степени 4 = 81
3 в степени 5 = 243
3 в степени 6 = 729
3 в степени 7 = 2187
3 в степени 8 = 6561
3 в степени 9 = 19683
3 в степени 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.
Получor цикл в цикле. Подобные конструкции весьма частые. Для завершающего примера построим таблицу умножения, которые школьники 90-х видели на обложках тетрадей в младших классах.
运算符 while - 3
public static void main(String[] args) {
    // Display the values ​​of the second multiplier in the line
    System.out.println("    2  3  4  5  6  7  8  9");
    int i = 2;      // first multiplier, assign starting value
    while(i<10) {   // First loop, execute while the first multiplier is less than 10
        System.out.print(i + " | ");// Display the first multiplier at the beginning of the string
        int j = 2;                  // second multiplier, starting value
        while (j<10) { // Second loop, execute while the second multiplier is less than 10
            int mul=i*j; // Calculate the product of factors
            if (mul<10)  // If it contains one digit, print two spaces after it
                System.out.print(mul + "  ");
            else   // otherwise output the product and after it - one space
                System.out.print(mul + " ");
            j++;     // Increase the second multiplier by one,
        }            // Go to the beginning of the second loop (while (j<10 ).... )
        System.out.println(); // Move to the next line of output
        i++;                  // Increase the first multiplier by one,
    }                         // Go to the beginning of the first loop (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) – один из фундаментальных кирпичиков построения программ. Решая задачи на JavaRush, вы изучите все их разнообразие, разберёте тонкости функционирования и получите практические навыки их применения.
评论
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION