循环
1. for 循环
通常用于已知循环次数的情况。
public class ForLoopExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) { //初始化; 条件; 更新
System.out.println("循环次数: " + i);
}
}
}
2. while 循环
条件为真时重复执行循环体。
public class WhileLoopExample {
public static void main(String[] args) {
int count = 1;
while (count <= 5) { //条件
System.out.println("循环次数: " + count);
count++; // 更新计数器
}
}
}
3. do-while 循环
确保至少执行一次循环体
public class DoWhileLoopExample {
public static void main(String[] args) {
int count = 1;
do {
System.out.println("循环次数: " + count);
count++; // 更新计数器
} while (count <= 5);
}
}
4. 增强型 for 循环(for each循环)
用于遍历数组或集合。
public class EnhancedForLoopExample {
public static void main(String[] args) {
String[] fruits = {"苹果", "香蕉", "橙子"};
for (String fruit : fruits) { //元素类型 变量名 : 数组或集合
System.out.println("水果: " + fruit);
}
}
}
5. 循环控制语句
-
break:用于跳出循环。
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // 当 i 为 5 时,退出循环
}
System.out.println(i);
}
-
continue:用于跳过当前循环的剩余部分,进入下一次循环。
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue; // 当 i 为 3 时,跳过当前循环
}
System.out.println(i);
}