Java 中循环控制结构有 3 种形式:forwhiledo-while

1. 循环语句

1.1 for循环

for循环的标准结构比较简单,包含循环变量的定义、终止条件以及循环体,我们直接来看一个示例:

  1. public class LoopFor {
  2. public static void main(String[] args) {
  3. for (int i = 1; i <= 5; i++) {
  4. System.out.println("This loop is " + i);
  5. }
  6. }
  7. }

1.1.1 for循环变体

当然,我们也可以将循环变量定义在外面,或者将循环体定义在大括号里面:

  1. public class LoopFor {
  2. public static void main(String[] args) {
  3. int i = 1;
  4. for (; i <= 5; i++;) {
  5. System.out.println("This loop is " + i);
  6. }
  7. }
  8. }
  1. public class LoopFor {
  2. public static void main(String[] args) {
  3. int i = 1;
  4. for (; i <= 5;) {
  5. System.out.println("This loop is " + i);
  6. i++;
  7. }
  8. }
  9. }

🔔 其他的改写形式可以自行尝试一下。

1.2 foreach

对于for循环而言,还有一种foreach的形式(也叫做增强for循环),这个其实是集合的一种遍历形式:

  1. public class LoopForeach {
  2. public static void main(String[] args) {
  3. int[] nums = {1, 2, 3, 4, 5};
  4. for (int num : nums) {
  5. System.out.println(num);
  6. }
  7. }
  8. }

1.3 嵌套for循环

嵌套for循环其实很简单,在for循环中再嵌套一个for循环,下面我们实现一个九九乘法表:

  1. for (int i = 1; i < 10; i++) {
  2. for (int j = 1; j <= i; j++) {
  3. System.out.print(i + "*" + j + "=" + i*j + " ");
  4. }
  5. System.out.println();
  6. }

🔔 嵌套for循环建议最多 3 层,否则算法的时间和空间复杂度会变得很高。

1.4 给for循环打标签

在嵌套for循环中,如果我们想要跳出外层for循环,这需要给for循环打上标签,然后使用break <tag>来跳出外层for循环。

  1. public class ForTag {
  2. public static void main(String[] args) {
  3. loop: for (int i = 0; i < 10; i ++) {
  4. for (int j = 1; j < 5; j ++) {
  5. if (i == 3 && j == 3) {
  6. break loop;
  7. }
  8. System.out.println("i=" + i + ", j= " + j);
  9. }
  10. }
  11. }
  12. }

2. while

while循环其实和for循环很相似,不一样的点是在于循环变量的定义和循环体的位置:

  1. public class LoopWhile {
  2. public static void main(String[] args) {
  3. int i = 0;
  4. while (i < 10) {
  5. System.out.println(i);
  6. i++;
  7. }
  8. }
  9. }

如果终止条件修改为true,则表示一直循环且不会终止,除非在循环体中手动break

3. do-while

do-while只是while的一种变种,两者的区别在于:

  • while是先判断终止条件是否满足,如果不满足的话就进入循环
  • do-while是先进行循环,然后判断终止条件是否满足,不满足的话就继续进入循环,也就说do-while一定会进行至少 1 次循环
  1. public class LoopDoWhile {
  2. public static void main(String[] args) {
  3. int i = 1;
  4. do {
  5. System.out.println(i);
  6. i++;
  7. } while (i < 1);
  8. }
  9. }

4. break / continue

在上面循环示例中,我们演示了在某些情况下可能想要跳过本次循环,继续下一次循环,或者提前结束掉全部循环。

Java 给我们提供了breakcontinue来完成对应的功能,且这两者都可以在forwhiledo-while循环中进行使用,其中:

  • continue:退出本次循环,继续下一次循环
  • break:退出全部循环

那么如果我们使用的是嵌套for循环的话,则使用break <tag>来跳出