SJC-P対策 フロー制御
フロー制御
javaのif文で評価する式は、必ずブールで無ければいけない。
つまり真か、偽のどちらかを評価しなければいけない。
次の式はコンパイルエラーとなる。
int x = 10; if(x) {} //整数値を評価する事は出来ない if(x = 0) {} //これもダメ |
ブール型変数に関しては、if文で代入した結果を
そのまま条件式として評価する事が出来る。
boolean b = false; if(b) {} //この式は有効 if(b = true) {} //この式も有効... //ただし注意しなければいけないこの式は //if(b == true)のつもりであったと考えられる |
switch文
switchのケース式には、同じ定数を使用することは出来ない。
int x = 10; switch(x) { case 1: break; case 2: break; case 3: break; case 3: break; //コンパイルエラー } |
フォールスルーはCと同じで、break文が見つかるまで
次々とケース式を実行する。
int x = 1; switch(x) { case 1: System.out.println("case 1"); case 2: System.out.println("case 2"); case 3: System.out.println("case 3"); case 4: System.out.println("case 4"); } |
case 1 case 2 case 3 case 4 |
switchのケース式に使えるのは、finalな変数、定数、enumに限る。
反復式
殆どの反復式は、Cと同じである。javaのfor文は、反復式の中で変数を宣言できる。
拡張for文を使う事も出来る。
for(int x = 0;x < 10;x++); |
int [] arr = {10, 20, 30, 40, 50 }; for(int x : arr) System.out.println(x); |
この拡張for文は、foreachと呼ばれ、配列やコンテナのみに
使う事が出来る。一見すると解りづらいので、Cに書き換えてみる。
//int [] arr = {10, 20, 30, 40, 50 }; //for(int x : arr); int x[] = {1,2,3,4,5}; int n; int i; for(i = 0;i < sizeof(x)/sizeof(x[0]);i++) { n = x[i]; //処理... } |