跳轉到內容

條件語句塊

100% developed
來自 Wikibooks,開放世界開放書籍

導航 語言基礎 主題:v  d  e )


條件語句塊允許程式根據某些條件選擇不同的執行路徑。它們允許程式執行一個測試,然後根據測試結果採取行動。在程式碼部分中,實際執行的程式碼行將被突出顯示。

如果

[edit | edit source]

if 程式碼塊僅在與之關聯的布林表示式為真時才執行。if 程式碼塊的結構如下所示

if (boolean expression1) {
statement1
statement2
...
statementn

}

以下是一個雙重示例,說明如果條件為真和條件為假時會發生什麼

Example 程式碼部分 3.22:兩個 if 程式碼塊。
int age = 6;
System.out.println("Hello!");

if (age < 13) {
  System.out.println("I'm a child.");
}

if (age > 20) {
  System.out.println("I'm an adult.");
}

System.out.println("Bye!");
Computer code 程式碼部分 3.22 的輸出
Hello!
I'm a child
Bye!
Note 如果 if 程式碼塊之後只執行一條語句,則無需將其括在花括號中。例如,if (i == 0) i = 1; 是 Java 程式碼的有效部分。這適用於大多數控制結構,例如 elsewhile。但是,Oracle 的 Java 程式碼約定 明確規定應始終使用花括號。

If/else

[edit | edit source]

if 程式碼塊可以可選地後接一個 else 程式碼塊,該程式碼塊將在該布林表示式為假時執行。if 程式碼塊的結構如下所示

if (boolean expression1) {
statement1
statement2
...
statementn

} else {

statement1bis
statement2bis
...
statementnbis

}


If/else-if/else

[edit | edit source]

當需要檢查多個條件時,可以使用 else-if 程式碼塊。else-if 語句位於 if 程式碼塊之後,但在 else 程式碼塊之前。if 程式碼塊的結構如下所示

if (boolean expression1) {
statement1.1
statement1.2
...
statementn

} else if (boolean expression2) {

statement2.1
statement2.2
...
statement2.n

} else {

statement3.1
statement3.2
...
statement3.n

}

以下是一個說明示例

Computer code 程式碼清單 3.3:MyConditionalProgram.java
public class MyConditionalProgram {
    public static void main (String[] args) {
      int a = 5;
      if (a > 0) {
          // a is greater than 0, so this statement will execute
          System.out.println("a is positive");
      } else if (a >= 0) {
          // a case has already executed, so this statement will NOT execute
          System.out.println("a is positive or zero");
      } else {
          // a case has already executed, so this statement will NOT execute
          System.out.println("a is negative");
      }
    }
}
Computer code 程式碼清單 3.3 的輸出
a is positive

請記住,只執行一個程式碼塊,它將是第一個為真的條件。

當遇到 if 時,會評估所有條件,無論條件的結果如何,在執行 if 程式碼塊之後。

Example 程式碼部分 3.23:變數 a 的新值。
int a = 5;
if (a > 0) {
    // a is greater than 0, so this statement will execute
    System.out.println("a is positive");
    a = -5;
} else if (a < 0) {
    // a WAS greater than 0, so this statement will not execute
    System.out.println("a is negative");
} else {
    // a does not equal 0, so this statement will not execute
    System.out.println("a is zero");
}
Computer code 程式碼部分 3.23 的輸出
a is positive

條件表示式

[edit | edit source]

條件表示式使用複合 ?: 運算子。語法

boolean expression1 ? expression1 : expression2

這將評估 boolean expression1,如果它為 true,則條件表示式將具有 expression1 的值;否則,條件表示式將具有 expression2 的值。

示例

Example 程式碼部分 3.24:條件表示式。
String answer = (p < 0.05)? "reject" : "keep";

這等效於以下程式碼片段

Example 程式碼部分 3.25:等效程式碼。
String answer;
if (p < 0.05) {
    answer = "reject";
} else {
    answer = "keep";
}

Switch

[edit | edit source]

switch 條件語句基本上是編寫許多 if...else 語句的簡寫版本。switch 程式碼塊評估一個 charbyteshortint(或 enum,從 J2SE 5.0 開始;或 String,從 J2SE 7.0 開始),並根據提供的值,跳轉到 switch 程式碼塊中的特定 case 並執行程式碼,直到遇到 break 命令或程式碼塊結束。如果 switch 值與任何 case 值都不匹配,則執行將跳轉到可選的 default case。

switch 語句的結構如下所示

switch (int1 或 char1 或 short1 或 byte1 或 enum1 或 String value1) {
case case value1
statement1.1
...
statement1.n
break;
case case value2
statement2.1
...
statement2.n
break;
default
statementn.1
...
statementn.n

}

以下是一個說明示例

Example 程式碼部分 3.26:一個 switch 程式碼塊。
int i = 3;
switch(i) {
    case 1:
        // i doesn't equal 1, so this code won't execute
        System.out.println("i equals 1");
        break;
    case 2:
        // i doesn't equal 2, so this code won't execute
        System.out.println("i equals 2");
        break;
    default:
        // i has not been handled so far, so this code will execute
        System.out.println("i equals something other than 1 or 2");
}
Computer code 程式碼部分 3.26 的輸出
i equals something other than 1 or 2

如果 case 沒有以 break 語句結尾,則將檢查下一個 case,否則執行將跳轉到 switch 語句的末尾。

檢視此示例以瞭解如何執行

Example 程式碼部分 3.27:一個包含沒有 breakcaseswitch 程式碼塊。
int i = -1;
switch(i) {
    case -1:
    case 1:
        // i is -1, so it will fall through to this case and execute this code
        System.out.println("i is 1 or -1");
        break;
    case 0:
        // The break command is used before this case, so if i is 1 or -1, this will not execute
        System.out.println("i is 0");
}
Computer code 程式碼部分 3.27 的輸出
i is 1 or -1

從 J2SE 5.0 開始,switch 語句也可以與 enum 值一起使用,而不是整數。

儘管尚未介紹 enums,但這裡有一個示例,以便您可以瞭解如何執行(請注意,case 中的 enum 常量不需要用型別限定

Example 程式碼部分 3.28:一個帶有 enum 型別的 switch 程式碼塊。
Day day = Day.MONDAY; // Day is a fictional enum type containing the days of the week
switch(day) {
    case MONDAY:
        // Since day == Day.MONDAY, this statement will execute
        System.out.println("Mondays are the worst!");
        break;
    case TUESDAY:
    case WEDNESDAY:
    case THURSDAY:
        System.out.println("Weekdays are so-so.");
        break;
    case FRIDAY:
    case SATURDAY:
    case SUNDAY:
        System.out.println("Weekends are the best!");
        break;
}
Computer code 程式碼部分 3.28 的輸出
Mondays are the worst!

從 J2SE 7.0 開始,switch 語句也可以與 String 值一起使用,而不是整數。

Example 程式碼部分 3.29:一個帶有 String 型別的 switch 程式碼塊。
String day = "Monday";
switch(day) {
    case "Monday":
        // Since day == "Monday", this statement will execute
        System.out.println("Mondays are the worst!");
        break;
    case "Tuesday":
    case "Wednesday":
    case "Thursday":
        System.out.println("Weekdays are so-so.");
        break;
    case "Friday":
    case "Saturday":
    case "Sunday":
        System.out.println("Weekends are the best!");
        break;
    default:
        throw new IllegalArgumentException("Invalid day of the week: " + day);
}
Computer code 程式碼部分 3.29 的輸出
Mondays are the worst!


華夏公益教科書