switch 语句

Java 中级

Jim White

Java Developer

什么是 switch?

  • switch 的作用类似 if-else
    • 根据条件执行操作
    • 用于替代多个 if-then-else
  • 比多个 if-then-else 更简洁
if (bonus == 10000) {
    System.out.println("Let's buy a car!");
} else if (bonus == 5000) {
    System.out.println("Let's take a trip!");
} else if (bonus == 1000) {
    System.out.println("Let's save!");
}
Java 中级

switch 语法

switch (expression) {
    case value1:  // if (expression == value1)
        // statements
    case value2:  // if (expression == value2)
        // statements
    // use as many case statements as needed
}
Java 中级

switch 示例

char direction = 'N';

switch (direction) {
    case 'E':  
        System.out.println("We are headed east.");
    case 'S':  
        System.out.println("We are headed south.");
    case 'W':  
        System.out.println("We are headed west.");
    case 'N':   
        System.out.println("We are headed north."); // This would be printed
}
Java 中级

break

  • 阻止 Java 继续执行后续分支
    • 没有 break,Java 会继续执行后续分支,直到遇到 break
char direction = 'W';

switch (direction) {
    case 'E':
        System.out.println("We are headed east.");
    case 'S':
        System.out.println("We are headed south.");
    case 'W':
        System.out.println("We are headed west."); // This would be printed
    case 'N':
        System.out.println("We are headed north."); // This would also be printed
}
Java 中级

break 可将多个分支合并处理:

char direction = 'N';

switch (direction) {
    case 'E':     
    case 'W':  
        System.out.println("We are headed east or west.");
        break;
    case 'S':  
    case 'N':
        System.out.println("We are headed south or north.");
        break;       
}
We are headed south or north.
Java 中级

default

  • 可在 switch 末尾添加可选的 default 分支
    • default 分支没有用于与表达式比较的值
    • 若无分支匹配表达式,将执行 default 的语句
    • default 必须是 switch 中的最后一个分支
  • default 表示"其他所有值"的分支
char direction = 'z';

switch (direction) {
  case 'E':     
  case 'W':  
    System.out.println("To east or west.");
    break;
  case 'S':  
  case 'N':
    System.out.println("To south or north.");
    break; 
  default:
    System.out.println("We are lost.");
}
We are lost.
Java 中级

条件语句 vs switch

  • 可用条件语句完成同样任务
  • 适用于所有数据类型
char character = 'A';
if (character == 'A') {
    System.out.println("It's A");
} else if (direction =='B') {
    System.out.println("It's B");
} else {
    System.out.println("Unknown");
}
  • switch 更易读
  • 仅适用于部分类型,如 intbyteshortcharString
char character = 'A';
switch (character) {
  case 'A':
    System.out.println("It's A");
    break;
  case 'B':  
    System.out.println("It's B");
    break;
  default:
    System.out.println("Unknown");
}
Java 中级

Passons à la pratique !

Java 中级

Preparing Video For Download...