Java 简明教程

Java - for Loop

Java for Loop

for 循环是一种重复控制结构,允许您高效地编写需要执行特定次数的循环。

A for loop is a repetition control structure that allows you to efficiently write a loop that needs to be executed a specific number of times.

当你了解任务重复多少次时,for 循环非常有用。就像 while loopfor 循环也是输入控制循环,其中给定的条件先执行。

A for loop is useful when you know how many times a task is to be repeated. Just like the while loop, the for loop is also an entry control loop where the given condition executes first.

Syntax of for Loop

for 循环的语法为:

The syntax of a for loop is −

for(initialization; Boolean_expression; update) {
   // Statements
}

Parts of Java For Loop

在 Java 中,for 循环使用三部分构造(实现)。以下是 Java 中 for 循环的部分:

In Java, the for loop is constructed (implemented) using three parts. The following are the parts of a for loop in Java -

  1. Initialization - Contains the initialization statement (s) of the loop counter.

  2. Boolean expression - Contains the condition to be tested.

  3. Body - Contains the statements to be iterated till the given Boolean expression is true, also to update the loop counter.

Execution Process of a for Loop

以下是 for 循环中的控制流程:

Here is the flow of control in a for loop −

  1. The initialization step is executed first, and only once. This step allows you to declare and initialize any loop control variables and this step ends with a semi colon (;).

  2. Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop will not be executed and control jumps to the next statement past the for loop.

  3. After the body of the for loop gets executed, the control jumps back up to the update statement. This statement allows you to update any loop control variables. This statement can be left blank with a semicolon at the end.

  4. The Boolean expression is now evaluated again. If it is true, the loop executes and the process repeats (body of loop, then update step, then Boolean expression). After the Boolean expression is false, the for loop terminates.

Flow Diagram

下图显示了 Java 中 for 循环的流程图(执行过程):

The following diagram shows the flow diagram (execution process) of a for loop in Java -

java for loop

Java for Loop Examples

Example 1: Printing Numbers in a Range Using for Loop

在这个示例中,我们将展示使用 for 循环打印从 10 到 19 开始的数字。这里我们在 for 循环的初始化块中将 int variable x 初始化为值 10。然后在表达式块中,我们检查 x 是否小于 20,最后在更新块中,我们将 x 增加 1。在 for 循环体内,我们将打印 x 的值。for 循环将一直运行,直到 x 变成 20。x 为 20 后,循环将停止执行并且程序退出。

In this example, we’re showing the use of a for loop to print numbers starting from 10 to 19. Here we’ve initialized an int variable x with a value of 10 within initialization blook of for loop. Then in expression block, we’re checking x as less than 20, and in the end under update block, we’re incrementing x by 1. Within body of for loop, we’re printing the value of x. For loop will run until x becomes 20. Once x is 20, loop will stop execution and program exits.

public class Test {

   public static void main(String args[]) {

      for(int x = 10; x < 20; x = x + 1) {
         System.out.print("value of x : " + x );
         System.out.print("\n");
      }
   }
}
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19

Example 2: Printing Array Elements Using for Loop

在这个示例中,我们将展示使用 for 循环打印 array 的内容。这里我们创建了一个整数数组作为 numbers,并对其初始化为一些值。我们创建了一个名为 index 的变量来表示 for 循环内的数组的索引,将它与数组大小进行比较并将其增加 1。在 for 循环体内,我们使用索引符号打印数组的元素。index 变成与数组大小相同时,for 循环退出并且程序退出。

In this example, we’re showing the use of a for loop to print contents of an array. Here we’re creating an array of integers as numbers and initialized it some values. We’ve created a variable named index to represent index of the array within for loop, check it against size of the array and incremented it by 1. Within for loop body, we’re printing element of the array using index notation. Once index becomes same as array size, for loop exits and program quits.

public class Test {

   public static void main(String args[]) {
      int [] numbers = {10, 20, 30, 40, 50};

      for(int index = 0; index < numbers.length; index++) {
         System.out.print("value of item : " + numbers[index] );
         System.out.print("\n");
      }
   }
}
value of item : 10
value of item : 20
value of item : 30
value of item : 40
value of item : 50

Java Infinite for Loop

无限循环永不结束,除非您通过按 CTRL + C 手动停止。要实现无限 for 循环,可以使用始终为真的条件或直接使用 true 作为条件。

An infinite loop never ends unless you stop manually by pressing CTRL + C. To implement an infinite for loop either use such a condition that is always true or directly use true as the condition.

Example: Implementing Infinite for Loop

在此示例中,我们展示了使用 for 循环的无限循环。它将继续打印数字,直到您按 Ctrl+c 终止程序。

In this example, we’re showing the infinite loop using for loop. It will keep printing the numbers until you press ctrl+c to terminate the program.

public class Test {

   public static void main(String args[]) {
      int x = 10;

      for( ;; ) {
         System.out.print("value of x : " + x );
         x++;
         System.out.print("\n");
      }
   }
}
value of item : 10
value of item : 11
value of item : 12
value of item : 13
value of item : 14
...
ctrl+c

Nested for Loop in Java

嵌套 for 循环是一个包含另一个 for 循环在其中的 for 循环。

A nested for loop is a for loop containing another for loop inside it.

Example: Print Tables from 1 to 10 Using Nested for Loop

在这个例子中,我们打印了从 1 到 10 的数字表格。

In this example, we are printing tables of the numbers from 1 to 10.

public class Main {
  public static void main(String[] args) {
    // Implementing nested for loop
    // Initializing loop counters
    int num = 1;
    int i = 1;

    // outer for loop
    for (num = 1; num <= 10; num++) {
      //inner for loop
      System.out.print("Table of " + num + " is : ");
      for (i = 1; i <= 10; i++) {
        // printing table
        System.out.print(num * i + " ");
      }
      // printing a new line
      System.out.println();
    }
  }
}
Table of 1 is : 1 2 3 4 5 6 7 8 9 10
Table of 2 is : 2 4 6 8 10 12 14 16 18 20
Table of 3 is : 3 6 9 12 15 18 21 24 27 30
Table of 4 is : 4 8 12 16 20 24 28 32 36 40
Table of 5 is : 5 10 15 20 25 30 35 40 45 50
Table of 6 is : 6 12 18 24 30 36 42 48 54 60
Table of 7 is : 7 14 21 28 35 42 49 56 63 70
Table of 8 is : 8 16 24 32 40 48 56 64 72 80
Table of 9 is : 9 18 27 36 45 54 63 72 81 90
Table of 10 is : 10 20 30 40 50 60 70 80 90 100