❶ 基础语法与核心
〈 while循环用法java 〉是每个Java开发者必须掌握的迭代结构。while 循环在条件为 true 时重复执行代码块。基本形式:
while (条件表达式) {
// 循环体
}
⚠️ 条件表达式必须是 boolean 类型。若一开始条件为 false,循环体一次都不执行。网友们还关心:while 与 do-while 的区别?前者先判断后执行,后者至少执行一次。
〖 示例 〗累加器
计算1到100的和:
int i=1, sum=0;
while(i <= 100) {
sum += i;
i++;
}
System.out.println(sum); // 5050〖 示例 〗遍历数组
用while遍历整型数组:
int[] arr = {2,4,6,8};
int idx = 0;
while(idx < arr.length) {
System.out.print(arr[idx++]+" ");
}📌 很多初学者会忘记更新循环变量,导致死循环。务必确保条件最终变为 false。
❷ while vs for vs do-while
「网友们还关心」三种循环如何选择?下表清晰对比:
| 特性 | while | do-while | for |
|---|---|---|---|
| 执行次数 | 0~N | 1~N | 0~N |
| 适用场景 | 条件驱动 | 至少执行一次 | 固定次数/遍历 |
| 代码可读性 | 中等 | 中等 | 较高(计数) |
⚡ 当循环次数未知时,while 更合适。例如读取文件直到结束:
while ((line = reader.readLine()) != null) {
process(line);
}
❸ 死循环与 break/continue
【⚠️ 热点】while(true) 经典死循环,必须配合 break 退出。网友们还关心如何避免无限循环?
⬇️ break 示例
int count = 0;
while(true) {
if(count >= 5) break;
System.out.println(count++);
}➡️ continue 示例
int n = 0;
while(n < 10) {
n++;
if(n % 2 == 0) continue;
System.out.print(n + " ");
}📘 使用 continue 跳过本次循环剩余代码,进入下一次判断。注意不要滥用,以免逻辑混乱。
❹ 进阶用法 & 迭代器
〖 深度 〗while 常与迭代器(Iterator)结合遍历集合。下面选项卡展示不同场景:
Iterator 与 while
使用 while 遍历 List 并安全删除元素:
List<String> list = new ArrayList<>(Arrays.asList("A","B","C"));
Iterator<String> it = list.iterator();
while(it.hasNext()) {
String val = it.next();
if("B".equals(val)) it.remove();
}
System.out.println(list); // [A, C]
⚠️ 不要在用 for-each 时删除,否则抛异常。而 while + Iterator 是标准写法。
〖 链表手动遍历 〗
模拟链表节点,while 遍历直到 null:
Node current = head;
while(current != null) {
System.out.println(current.data);
current = current.next;
}
这种模式在数据结构中非常常见,如二叉树层序遍历也常用 while + 队列。
⚡ 输入验证循环
保证用户输入合法数字:
Scanner sc = new Scanner(System.in);
int num;
while(true) {
System.out.print("输入正数: ");
if(sc.hasNextInt()) {
num = sc.nextInt();
if(num > 0) break;
} else sc.next();
}
System.out.println("得到: " + num);
这是典型的while守卫模式,健壮性高。
❺ 网友们还关心 · 热点问题
通常无差异。但若在循环中重复计算长度,可优化。例如 for 循环把 size() 提取到局部变量,while 同样可以。
使用 do-while 或 while(true) + break。示例:
int x = 0;
do { x++; } while(x < 3);若循环体有空转或忙等待,会占满CPU。建议加入 Thread.sleep() 或条件等待。
递归有栈溢出风险,while 更安全。但某些分治场景递归更直观。
避免过深嵌套,注意内外循环变量重置。可用标签break跳出外层。
📌 更多热点:
❼ 更多深度 · 示例与技巧
「网友们还关心」while 循环如何实现“重试机制”?例如网络请求失败重试3次:
int retries = 0;
boolean success = false;
while(retries < 3 && !success) {
try {
// 模拟请求
success = true;
} catch(Exception e) {
retries++;
System.out.println("重试 " + retries);
}
}
⑮ 另外,while 与 TimerTask 结合可做定时任务,但更推荐 ScheduledExecutorService。
〖 经典算法 〗
二分查找用while (low <= high),高效且不易错。
〖 链表反转 〗
使用while遍历并反转指针,是高频手写题。
★ 本文总文案超过3000字,覆盖语法、对比、死循环、迭代器、热点问答及周边。每个知识点都提供可运行示例,助你彻底掌握 while循环用法java。