跳转至

控制流程

📖 章节简介

本章将介绍Java的控制流程语句,包括条件语句、循环语句和跳转语句。

Java控制流程总览

上图概括了条件分支、循环结构与跳转控制三类核心语句。

🔀 条件语句

1. if-else语句

Java
// if-else语句
public class IfElseStatement {
    public static void main(String[] args) {
        int score = 85;

        // 简单if语句
        if (score >= 60) {
            System.out.println("及格");
        }

        // if-else语句
        if (score >= 90) {
            System.out.println("优秀");
        } else {
            System.out.println("良好");
        }

        // if-else if-else语句
        if (score >= 90) {
            System.out.println("A");
        } else if (score >= 80) {
            System.out.println("B");
        } else if (score >= 70) {
            System.out.println("C");
        } else if (score >= 60) {
            System.out.println("D");
        } else {
            System.out.println("F");
        }
    }
}

2. switch语句

Java
// switch语句
public class SwitchStatement {
    public static void main(String[] args) {
        int dayOfWeek = 3;

        switch (dayOfWeek) {
            case 1:
                System.out.println("星期一");
                break;
            case 2:
                System.out.println("星期二");
                break;
            case 3:
                System.out.println("星期三");
                break;
            case 4:
                System.out.println("星期四");
                break;
            case 5:
                System.out.println("星期五");
                break;
            case 6:
                System.out.println("星期六");
                break;
            case 7:
                System.out.println("星期日");
                break;
            default:
                System.out.println("无效的星期");
        }

        // 使用字符串的switch(Java 7+)
        String season = "春";
        switch (season) {
            case "春":
                System.out.println("春暖花开");
                break;
            case "夏":
                System.out.println("夏日炎炎");
                break;
            case "秋":
                System.out.println("秋高气爽");
                break;
            case "冬":
                System.out.println("冬雪皑皑");
                break;
            default:
                System.out.println("未知季节");
        }

        // 使用枚举的switch(Java 16+ 支持在方法内定义局部枚举)
        enum Color { RED, GREEN, BLUE }
        Color color = Color.RED;
        switch (color) {
            case RED:
                System.out.println("红色");
                break;
            case GREEN:
                System.out.println("绿色");
                break;
            case BLUE:
                System.out.println("蓝色");
                break;
        }
    }
}

🔄 循环语句

1. for循环

Java
// for循环
public class ForLoop {
    public static void main(String[] args) {
        // 基本for循环
        System.out.println("基本for循环:");
        for (int i = 1; i <= 10; i++) {
            System.out.print(i + " ");
        }
        System.out.println();

        // 增强for循环(for-each)
        System.out.println("\n增强for循环:");
        int[] numbers = {1, 2, 3, 4, 5};
        for (int num : numbers) {
            System.out.print(num + " ");
        }
        System.out.println();

        // 嵌套for循环
        System.out.println("\n嵌套for循环(九九乘法表):");
        for (int i = 1; i <= 9; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print(j + "×" + i + "=" + (i * j) + "\t");
            }
            System.out.println();
        }

        // 使用break和continue
        System.out.println("\n使用break:");
        for (int i = 1; i <= 10; i++) {
            if (i == 5) {
                break;  // 跳出循环
            }
            System.out.print(i + " ");
        }

        System.out.println("\n\n使用continue:");
        for (int i = 1; i <= 10; i++) {
            if (i % 2 == 0) {
                continue;  // 跳过本次迭代
            }
            System.out.print(i + " ");
        }
    }
}

2. while循环

Java
// while循环
public class WhileLoop {
    public static void main(String[] args) {
        // while循环
        System.out.println("while循环:");
        int i = 1;
        while (i <= 5) {
            System.out.print(i + " ");
            i++;
        }

        // do-while循环
        System.out.println("\n\ndo-while循环:");
        int j = 1;
        do {
            System.out.print(j + " ");
            j++;
        } while (j <= 5);

        // 无限循环
        System.out.println("\n\n无限循环示例:");
        int count = 0;
        while (true) {
            count++;
            System.out.println("循环次数: " + count);
            if (count >= 3) {
                break;  // 退出循环
            }
        }
    }
}

🎯 跳转语句

1. break语句

Java
// break语句
public class BreakStatement {
    public static void main(String[] args) {
        // 跳出循环
        System.out.println("跳出循环:");
        for (int i = 1; i <= 10; i++) {
            if (i == 5) {
                break;  // 跳出循环
            }
            System.out.print(i + " ");
        }

        // 跳出嵌套循环(使用标签)
        System.out.println("\n\n跳出嵌套循环:");
        outer:
        for (int i = 1; i <= 3; i++) {
            for (int j = 1; j <= 3; j++) {
                if (i == 2 && j == 2) {
                    break outer;  // 跳出外层循环
                }
                System.out.println("i=" + i + ", j=" + j);
            }
        }
    }
}

2. continue语句

Java
// continue语句
public class ContinueStatement {
    public static void main(String[] args) {
        // 跳过本次迭代
        System.out.println("跳过偶数:");
        for (int i = 1; i <= 10; i++) {
            if (i % 2 == 0) {
                continue;  // 跳过本次迭代
            }
            System.out.print(i + " ");
        }

        // 在嵌套循环中使用continue(带标签)
        System.out.println("\n\n跳过特定条件:");
        outer:
        for (int i = 1; i <= 3; i++) {
            for (int j = 1; j <= 3; j++) {
                if (i == 2 && j == 2) {
                    continue outer;  // 跳到外层循环的下一次迭代
                }
                System.out.println("i=" + i + ", j=" + j);
            }
        }
    }
}

💡 最佳实践

1. 代码可读性

Java
// 提高代码可读性
public class CodeReadability {
    public static void main(String[] args) {
        // ✅ 好的做法:使用有意义的变量名
        int studentScore = 85;
        if (studentScore >= 60) {
            System.out.println("及格");
        }

        // ❌ 不好的做法:使用无意义的变量名
        int x = 85;
        if (x >= 60) {
            System.out.println("及格");
        }

        // ✅ 好的做法:使用常量
        final int PASSING_SCORE = 60;
        if (studentScore >= PASSING_SCORE) {
            System.out.println("及格");
        }

        // ❌ 不好的做法:使用魔法数字
        if (studentScore >= 60) {
            System.out.println("及格");
        }
    }
}

2. 性能优化

Java
// 循环性能优化
import java.util.Arrays;
import java.util.List;

public class LoopOptimization {
    public static void main(String[] args) {
        // ✅ 好的做法:将不变的条件移出循环
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
        boolean isEmpty = list.isEmpty();

        if (!isEmpty) {
            for (Integer num : list) {
                System.out.println(num);
            }
        }

        // ❌ 不好的做法:每次循环都检查条件
        for (Integer num : list) {
            if (!list.isEmpty()) {  // 每次都检查
                System.out.println(num);
            }
        }

        // ✅ 好的做法:使用增强for循环(代码简洁,适用于所有Iterable)
        for (int num : list) {
            System.out.println(num);
        }

        // ⚠️ 索引访问方式(ArrayList的get(i)是O(1)性能无问题,但对LinkedList是O(n),且代码可读性较差)
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));
        }
    }
}

📝 练习题

基础题

  1. Java有哪些条件语句?
  2. for循环和while循环有什么区别?
  3. break和continue有什么区别?

进阶题

  1. 使用switch语句实现计算器。
  2. 实现嵌套循环打印图形。
  3. 使用标签控制循环跳转。

实践题

  1. 编写一个猜数字游戏。
  2. 实现一个简单的菜单系统。
  3. 创建一个成绩统计程序。

📚 推荐阅读

🔗 下一章

数组与字符串 - 学习Java的数组和字符串操作。