📜  java中的所有循环(1)

📅  最后修改于: 2023-12-03 14:42:57.396000             🧑  作者: Mango

Java中的所有循环

在Java中,循环是非常常用的语言结构之一。它们允许代码多次执行,而不必显式重复相同的代码。Java中有四种主要的循环类型:for、while、do-while和for-each。

for循环

for循环是最常用的循环结构之一。它允许我们在指定一定的次数下重复执行一段代码。for循环的语法如下:

for (initialization; condition; update) {
    // code to be executed
}
  • initialization:初始化代码块,只会在循环开始前执行一次。通常用于初始化循环计数器。
  • condition:循环条件,如果为true,则循环继续执行,否则循环停止。
  • update:更新语句,每次循环完成后执行一次。通常用于增加或减少循环计数器的值。

例如,下面的代码使用for循环输出1到5:

for (int i = 1; i <= 5; i++) {
    System.out.println(i);
}

// Output:
// 1
// 2
// 3
// 4
// 5
while循环

while循环是在条件为真的情况下重复执行一段代码。while循环的语法如下:

while (condition) {
    // code to be executed
}
  • condition:循环条件,如果为true,则循环继续执行,否则循环停止。

例如,下面的代码使用while循环输出1到5:

int i = 1;
while (i <= 5) {
    System.out.println(i);
    i++;
}

// Output:
// 1
// 2
// 3
// 4
// 5
do-while循环

do-while循环是先执行一次代码块,然后只要条件为真就重复执行。do-while循环的语法如下:

do {
    // code to be executed
} while (condition);
  • condition:循环条件,如果为true,则循环继续执行,否则循环停止。

例如,下面的代码使用do-while循环输出1到5:

int i = 1;
do {
    System.out.println(i);
    i++;
} while (i <= 5);

// Output:
// 1
// 2
// 3
// 4
// 5
for-each循环

for-each循环是用于迭代数组或集合中的每个元素。for-each循环的语法如下:

for (type var : array) {
    // code to be executed
}
  • type:数组或集合中元素的类型。
  • var:变量名,用于存储每个元素的值。
  • array:数组或集合的名称。

例如,下面的代码使用for-each循环遍历数组,并计算其中所有元素的和:

int[] numbers = {1, 2, 3, 4, 5};
int sum = 0;

for (int num : numbers) {
    sum += num;
}

System.out.println("Sum: " + sum);

// Output:
// Sum: 15

以上是Java中常用的四种循环类型。根据实际需求,选择适当的循环类型可以帮助我们更加高效地编写代码。