在 Java 中,條件語句的格式爲:
if(condition) statement
這裏的條件必須用小括號括起來。java
Java 經常但願在某個條件爲真時執行多條語句。在這種狀況下,就能夠使用塊語句(block statement),形式爲:ide
if(condition) { statement1 statement2 . . . }
例如:3d
if(yourSales > target) { berformance = "Satisfactory"; bonus = 100; }
在 Java 中,更通常的條件語句以下所示:
if(condition) statement1 else statement2
其中 else 部分老是可選的。code
if(yourSales > target) { berformance = "Satisfactory"; bonus = 100; } else { performance = "Unsatisfactory"; bonus = 0 }
反覆使用 if...else if... 很常見,else 子句與最近的 if 構成一組。orm
if(yourSales >= 2 * target) { berformance = "Excellent"; bonus = 1000; } else if(yourSales >= 1.5 * target) { berformance = "Fine"; bonus = 500; } else if(yourSales >= target) { berformance = "Satisfactory"; bonus = 100; } else { System.out.pritnln("You're fired") }