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が残りのcaseへ進むのを止める
    • breakがないと、次の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ケースを追加できる
    • defaultは式と比較する値を持たない
    • どのcaseにも一致しない場合、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

if文と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

Ayo berlatih!

中級 Java

Preparing Video For Download...