while 关键字
概述
while
关键字用于创建条件循环,当条件为true时重复执行代码块。
语法格式
while (条件表达式) {
// 循环体
}
基本用法
public class WhileExample {
public static void main(String[] args) {
// 基本while循环
int i = 0;
while (i < 5) {
System.out.println("i = " + i);
i++;
}
// 使用while查找数组元素
int[] numbers = {1, 3, 5, 7, 9};
int target = 5;
int index = 0;
boolean found = false;
while (index < numbers.length && !found) {
if (numbers[index] == target) {
found = true;
System.out.println("找到元素 " + target + " 在索引 " + index);
}
index++;
}
}
}
与do-while的区别
public class WhileVsDoWhile {
public static void main(String[] args) {
// while循环 - 可能不执行
int x = 10;
while (x < 5) {
System.out.println("while: " + x); // 不会执行
x++;
}
// do-while循环 - 至少执行一次
do {
System.out.println("do-while: " + x); // 会执行一次
x++;
} while (x < 5);
}
}
while循环适用于事先不知道循环次数的情况,是Java中重要的控制结构。