Switch 陳述式

Java 中級

Jim White

Java Developer

什麼是 switch?

  • switchif-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 繼續執行後續的 case。
    • 若無 break,Java 會往下個 case 繼續執行,直到遇到 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 可將多個 case 合併處理:

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

  • default 可選,通常放在 switch 的最後。
    • default 不與任何值比較
    • 若沒有 case 符合,會執行 default 的敘述
    • default 必須是 switch 的最後一個 case
  • 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 中級

一起來練習吧!

Java 中級

Preparing Video For Download...