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 | public class CH0701 { public static void main(String[] args) { int score = 88 ; if (score >= 90 ) { System.out.printf( "A" ); } else if (score >= 80 && score < 90 ) { System.out.printf( "B" ); } else if (score >= 70 && score < 80 ) { System.out.printf( "C" ); } else if (score >= 60 && score < 70 ) { System.out.printf( "D" ); } else { System.out.printf( "E" ); } } } |
鏈狀效率並不好,上面的例子在最差的情況下要存取並運算7次。
switch運算函數當中置放變數或運算式,判斷後會開始與case中設定的值比對。如果相符合就執行大括號程式碼區塊,程式碼需要加「break」就離開。若沒有符合的條件,則會執行「default」後的陳述句。「default」不一定需要,如果沒有預設要處理的動作,可以省略「default」。
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 32 33 34 | public class CH0702{ public static void main(String[] args) { int score = 100 ; int quotient = score / 10 ; switch (quotient) { case 10 : case 9 : System.out.printf( "A" ); break ; case 8 : System.out.printf( "B" ); break ; case 7 : System.out.printf( "C" ); break ; case 6 : System.out.printf( "D" ); break ; default : System.out.printf( "E" ); } } } |
case 10 沒有任何的陳述,也沒有使用break,所以程式繼續往下執行,直到遇到了「break」離開「switch」。當成績為 100 顯示 case 9: break之前的程式碼。如果比對條件不在6, 7, 8, 9這些數字的話,會執行 default: 後方的程式碼。
沒有留言:
張貼留言