switchを使って処理の流れを制御する
switchを使うとフロー制御に複数の条件を記述する事が出来ます。
case文では32bit以下の整数のみ使用可能です。float型や参照型、式などを使う事は出来ません。
class ExamSwitch {
public static void main(String args[]) {
int i1 = 1;
switch (i1) {
case 0 :
System.out.println("i1 = 0");
case 1 :
System.out.println("i1 = 1");
case 2 :
System.out.println("i1 = 2");
default :
System.out.println("i1 = other");
}
}
}
class ExamSwitch1 {
public static void main(String args[]) {
int i1 = 1;
switch (i1) {
case 0 :
System.out.println("i1 = 0");
break;
case 1 :
System.out.println("i1 = 1");
break;
case 2 :
System.out.println("i1 = 2");
break;
default :
System.out.println("i1 = other");
}
}
}
class ExamSwitch2 {
public static void main(String args[]) {
int i1 = 1;
switch (i1) {
case 0 :
case 1 :
case 2 :
case 3 :
case 4 :
case 5 :
System.out.println("i1 is number");
break;
default :
System.out.println("i1 is not number");
}
}
}
<実行結果>
| @ ExamSwitch | コンソールに i1 = 1 i1 = 2 i1 = other と表示されます。 |
case文では、条件に該当する行が有ると、それ以降の行は全て真と評価され、残りの行の処理が全て実行されます。 default文は省略可能で、変数の値がどのcaseにも一致しない場合、default文の処理が実行されます。 |
| A ExamSwitch1 | コンソールに i1 = 1 と表示されます。 |
break文を使うと制御がswitch文の外に移ります。 |
| B ExamSwitch2 | コンソールに i1 is number と表示されます。 |
この様にcase文を使うと、1つの分岐について複数の値を記述することになります。 (ソースコードが冗長になるので6以上は条件を書きませんでした。) |