Skip to content
第 3 章 后端 ⏱ 15 分钟阅读

第 3 章:流程控制、方法与数组 ​

学习目标 ​

  • 掌握 if-else / switch / for / while 流程控制
  • 学会定义方法、调用方法、重载
  • 理解数组和 Arrays 工具类
  • 避开流程控制和数组的常见坑

一、if-else 分支 ​

java
int score = 85;

if (score >= 90) {
    System.out.println("优秀");
} else if (score >= 60) {
    System.out.println("及格");
} else {
    System.out.println("不及格");
}

⚠️ 坑 1:嵌套不要超过 3 层,否则用卫语句提前 return:

java
public void buy(int age, boolean hasId) {
    if (age < 18) { System.out.println("未成年"); return; }   // ① 先处理特殊
    if (!hasId) { System.out.println("没带身份证"); return; }
    System.out.println("可以买");                              // ② 主逻辑在最后
}

二、switch 等值判断 ​

JDK 14+ 推荐箭头语法(不穿透,不用 break):

java
int day = 3;
String name = switch (day) {
    case 1 -> "周一";
    case 2 -> "周二";
    case 6, 7 -> "周末";
    default -> "工作日";
};

⚠️ 坑 2:老式 switch 必须 break,否则从匹配的 case 穿透到底,会把后面的 case 全执行一遍。

三、循环 ​

for(已知次数) ​

java
for (int i = 1; i <= 5; i++) {
    System.out.println(i);
}

for-each(遍历数组/集合,首选) ​

java
int[] arr = {1, 2, 3};
for (int num : arr) {
    System.out.println(num);
}

while(未知次数) ​

java
int i = 0;
while (i < 5) {
    System.out.println(i);
    i++;
}

do-while(至少执行一次) ​

java
Scanner sc = new Scanner(System.in);
int choice;
do {
    System.out.print("输入 1-3: ");
    choice = sc.nextInt();
} while (choice < 1 || choice > 3);

break / continue ​

java
for (int i = 1; i <= 10; i++) {
    if (i == 3) continue;    // 跳过本次,进入下一轮
    if (i == 7) break;       // 跳出整个循环
    System.out.print(i + " ");  // 输出:1 2 4 5 6
}

⚠️ 坑 3:for (;;) { } 没 break 就是死循环,Ctrl+C 才能停。 ⚠️ 坑 4:遍历集合时别 add/remove,会抛 ConcurrentModificationException。

四、方法 ​

定义和调用 ​

java
public static int add(int a, int b) {       // static = 静态,同类可直接调用
    return a + b;
}

public static void main(String[] args) {
    int sum = add(3, 5);                     // 调用
    System.out.println(sum);                 // 8
}
  • void:无返回值,不用写 return 值
  • return 值:返回结果

方法重载(同名不同参) ​

java
public static int add(int a, int b) { return a + b; }
public static int add(int a, int b, int c) { return a + b + c; }   // 参数个数不同
public static double add(double a, double b) { return a + b; }    // 参数类型不同

只跟参数列表有关,跟返回类型无关。

值传递(Java 永远是值传递) ​

java
public static void swap(int a, int b) {
    int temp = a; a = b; b = temp;          // 交换的是副本
}

int x = 10, y = 20;
swap(x, y);
System.out.println(x + "," + y);            // 10,20(没换成功!)

引用类型传的是地址副本:

  • ✅ 可以通过引用改对象内容(user.setName("李四") 生效)
  • ❌ 不能改外部引用本身(user = null 不影响外面)

五、数组 ​

声明和初始化 ​

java
int[] scores = {85, 92, 78, 95, 88};      // 声明并初始化(最常用)
String[] names = new String[3];             // new + 长度,引用类型默认 null

访问和遍历 ​

java
int[] arr = {10, 20, 30};
arr[0]               // 10(下标从 0 开始)
arr.length           // 3(length 是属性,不是方法)

for (int i = 0; i < arr.length; i++) {     // 传统 for
    System.out.println(arr[i]);
}

for (int num : arr) {                      // for-each,推荐
    System.out.println(num);
}

Arrays 工具类 ​

java
import java.util.Arrays;

int[] arr = {3, 1, 4, 1, 5};
Arrays.sort(arr);                           // 排序
System.out.println(Arrays.toString(arr));   // 打印:[1, 1, 3, 4, 5]
Arrays.fill(arr, 0);                        // 全部填 0

数组与 List 互转 ​

java
String[] arr = {"a", "b", "c"};

// 数组 → List
List<String> list = new ArrayList<>(Arrays.asList(arr));  // 可变 List
list.add("d");                                             // ✅ 可以增删

// List → 数组
String[] newArr = list.toArray(new String[0]);

⚠️ 坑 5:Arrays.asList(arr) 返回的 List 长度固定,直接 add 会抛 UnsupportedOperationException,要包一层 new ArrayList<>()。 ⚠️ 坑 6:数组下标越界报 ArrayIndexOutOfBoundsException,有效范围是 0 ~ length-1。 ⚠️ 坑 7:数组 .length 是属性,字符串 .length() 才是方法,记混了编译报错。

六、实战:综合小练习 ​

java
/**
 * 找出数组中的最大值、最小值、平均分
 */
public static void analyze(int[] scores) {
    int max = scores[0];
    int min = scores[0];
    int sum = 0;
    for (int s : scores) {
        if (s > max) max = s;
        if (s < min) min = s;
        sum += s;
    }
    double avg = (double) sum / scores.length;   // ⚠️ 强转避免整数除法

    System.out.println("最高分:" + max);
    System.out.println("最低分:" + min);
    System.out.println("平均分:" + avg);
}

七、本章小结 ​

要点关键
if-else范围判断,嵌套不超过 3 层,优先用卫语句
switch等值判断,推荐 JDK 14+ 箭头语法
for / for-each已知次数用 for,遍历数组用 for-each
while未知次数,靠条件退出
方法重载同名不同参,只看参数列表
值传递Java 永远值传递,引用传地址副本
数组长度固定,.length 是属性

动手练习 ​

  1. 九九乘法表:用嵌套 for 打印
  2. 找数组最大值:写个 max(int[] arr) 方法,处理空数组异常
  3. 数组反转:写个 reverse(int[] arr),返回新数组
  4. 猜数字游戏:随机生成 1-100,用 while 让用户猜,提示大小直到猜中

下一章:第 4 章:类与对象 →

本站基于 VitePress 构建 · 由 StackHub 团队维护