[toc] https://docs.oracle.com/javase/tutorial/java/nutsandbolts/if.html # if/else 顧名思義,if 就是如果...,就... ``` if (boolean expression) // statement ``` --- 範例: ```java int a = 1; if (a == 1) System.out.print("hello world"); ``` --- 前篇說過, Block也算是一個statement. ```java int a = 1; if (a == 1) { System.out.print("hello world"); System.out.print("hello world!!!"); } ``` --- 如果要在 if 後面在新增更多種情況可以用 else if ```java int a = 5487; if (a > 10000) { System.out.print("too expensive"); } else if(a > 5000) { System.out.print("deal"); // 會執行這行 } ``` --- if或是if else都不成立, 可以接 else ```java int a = 3000; if (a > 10000) { System.out.print("too expensive"); } else if (a > 5000) { System.out.print("deal"); } else { System.out.print("cheapest is the dearest"); // 會執行這行 } ``` --- 不建議因為Block內只有一個敘述就省略大括號。 ```java int a = 1; if (a == 1) System.out.print("Hello World"); System.out.println("End of this section"); ``` 這樣寫比較好懂。 ```java int a = 1; if (a == 1) { System.out.print("Hello World"); } System.out.println("End of this section"); ``` --- 不能在非block的敘述內宣告變數。 ```java if (a > 10000) int i = 1; // not allowed ```