Java 中級
Jim White
Java Developer
switch 與 if-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!");
}
switch (expression) {
case value1: // if (expression == value1)
// statements
case value2: // if (expression == value2)
// statements
// use as many case statements as needed
}
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
}
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
}
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.
default 可選,通常放在 switch 的最後。default 不與任何值比較default 的敘述default 必須是 switch 的最後一個 casedefault 相當於「其他所有值」的處理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.
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 較易閱讀。int、byte、short、char、String。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 中級