reg_switch.d
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | import std.stdio;
import std.string;
void main(){
write("Enter Y/N > ");
char [] s = readln().dup;
s = chomp(s.idup).dup;
switch(s){
/*
switch 文は整数だけじゃなく文字列も使えてハッピー
*/
case "y", "Y", "yes":
/*
case 文にはカンマで区切って複数の値を指定可能
*/
writeln("Yes"); break;
/*
fall through するので break は必要
*/
case "n", "N", "no":
writeln("No"); break;
default:
writeln("...?");
/*
D 言語では default がないと該当する case がないときに
実行時にエラーになるのでちゃんと書くべき.
*/
}
}
|
reg_switch.d の実行結果は:
[cactus:~/code_d/d_tuts]% ./reg_switch
Enter Y/N > y
Yes
[cactus:~/code_d/d_tuts]% ./reg_switch
Enter Y/N > Y
Yes
[cactus:~/code_d/d_tuts]% ./reg_switch
Enter Y/N > n
No
[cactus:~/code_d/d_tuts]% ./reg_switch
Enter Y/N > N
No
final_switch.d
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | import std.stdio;
enum Color{ RED, YELLOW, GREEN}
void main(){
int i;
Color c = Color.RED;
while(i < 9){
final switch(c){
case Color.RED:
c = Color.YELLOW;
writeln("SIGNAL is YELLOW");
break;
case Color.YELLOW:
c = Color.GREEN;
writeln("SIGNAL is GREEN");
break;
case Color.GREEN:
c = Color.RED;
writeln("SIGNAL is RED");
break;
/*
final switch には default は書けない.
*/
}
i++;
}
}
|
final_switch.d の実行結果は:
[cactus:~/code_d/d_tuts]% ./final_switch
SIGNAL is YELLOW
SIGNAL is GREEN
SIGNAL is RED
SIGNAL is YELLOW
SIGNAL is GREEN
SIGNAL is RED
SIGNAL is YELLOW
SIGNAL is GREEN
SIGNAL is RED