1.for循环
for (int i = 0; i < 10; i++) {
System.out.println("当前循环次数:" + i);
}
2.while循环: while循环是一种在未知循环次数的情况下执行特定代码块的循环语句。while循环在每次迭代之前检查循环条件是否为真,如果为真则执行代码块。示例代码如下:
int i = 0;
while (i < 5) {
System.out.println("当前循环次数:" + i);
i++;
}
3.do-while循环: do-while循环是一种与while循环类似的循环语句,不同之处在于它先执行一次代码块,然后再检查循环条件。示例代码如下:
int i = 0;
do {
System.out.println("当前循环次数:" + i);
i++;
} while (i < 5);
除了上述三种基本的循环语句外,Java还提供了break和continue语句用于控制循环的执行流程。break语句用于立即退出循环,而continue语句用于跳过当前迭代并继续下一次迭代。在编写循环时,务必注意循环条件的正确性,以避免出现死循环的情况。
假设有一个整数数组,我们需要遍历数组并输出其中的偶数。以下是一个示例代码:
public class Main {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// 使用for循环遍历数组并输出偶数
System.out.println("使用for循环输出偶数:");
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] % 2 == 0) {
System.out.println(numbers[i]);
}
}
// 使用while循环遍历数组并输出偶数
System.out.println("使用while循环输出偶数:");
int j = 0;
while (j < numbers.length) {
if (numbers[j] % 2 == 0) {
System.out.println(numbers[j]);
}
j++;
}
// 使用do-while循环遍历数组并输出偶数
System.out.println("使用do-while循环输出偶数:");
int k = 0;
do {
if (numbers[k] % 2 == 0) {
System.out.println(numbers[k]);
}
k++;
} while (k < numbers.length);
}
}
在上面的示例中,我们定义了一个整数数组numbers
,然后使用for循环、while循环和do-while循环分别遍历数组并输出其中的偶数。您可以根据需要修改数组内容或循环条件来测试不同的情况。