Java 控制語句

Java 控制語句

📓 本文已歸檔到:「javacore

🔁 本文中的示例代碼已歸檔到:「javacore

Java 控制語句大致可分爲三大類:

- 選擇語句

- if, else-if, else

- switch

- 循環語句

- while

- do...while

- for

- foreach

- 終端語句

- break

- continue

- return

1. 選擇語句

1.1. if 語句

if 語句會判斷括號中的條件是否成立,如果成立則執行 if 語句中的代碼塊,否則跳過代碼塊繼續執行。

語法

if(布爾表達式) {
   //如果布爾表達式爲true將執行的語句
}

示例

public class IfDemo {
    public static void main(String args[]) {
        int x = 10;
        if (x < 20) {
            System.out.print("這是 if 語句");
        }
    }
}
// output:
// 這是 if 語句

1.2. if...else 語句

if 語句後面可以跟 else 語句,當 if 語句的布爾表達式值爲 false 時,else 語句塊會被執行。

語法

if(布爾表達式) {
   //如果布爾表達式的值爲true
} else {
   //如果布爾表達式的值爲false
}

示例

public class IfElseDemo {
    public static void main(String args[]) {
        int x = 30;
        if (x < 20) {
            System.out.print("這是 if 語句");
        } else {
            System.out.print("這是 else 語句");
        }
    }
}
// output:
// 這是 else 語句

1.3. if...else if...else 語句

  • if 語句至多有 1 個 else 語句,else 語句在所有的 else if 語句之後。
  • If 語句可以有若干個 else if 語句,它們必須在 else 語句之前。
  • 一旦其中一個 else if 語句檢測爲 true,其他的 else if 以及 else 語句都將跳過執行。

語法

if (布爾表達式 1) {
   //如果布爾表達式 1的值爲true執行代碼
} else if (布爾表達式 2) {
   //如果布爾表達式 2的值爲true執行代碼
} else if (布爾表達式 3) {
   //如果布爾表達式 3的值爲true執行代碼
} else {
   //如果以上布爾表達式都不爲true執行代碼
}

示例

public class IfElseifElseDemo {
    public static void main(String args[]) {
        int x = 3;

        if (x == 1) {
            System.out.print("Value of X is 1");
        } else if (x == 2) {
            System.out.print("Value of X is 2");
        } else if (x == 3) {
            System.out.print("Value of X is 3");
        } else {
            System.out.print("This is else statement");
        }
    }
}
// output:
// Value of X is 3

1.4. 嵌套的 if…else 語句

使用嵌套的 if else 語句是合法的。也就是說你可以在另一個 if 或者 else if 語句中使用 if 或者 else if 語句。

語法

if (布爾表達式 1) {
   ////如果布爾表達式 1的值爲true執行代碼
   if (布爾表達式 2) {
      ////如果布爾表達式 2的值爲true執行代碼
   }
}

示例

public class IfNestDemo {
    public static void main(String args[]) {
        int x = 30;
        int y = 10;

        if (x == 30) {
            if (y == 10) {
                System.out.print("X = 30 and Y = 10");
            }
        }
    }
}
// output:
// X = 30 and Y = 10

1.5. switch 語句

switch 語句判斷一個變量與一系列值中某個值是否相等,每個值稱爲一個分支。

switch 語句有如下規則:

  • switch 語句中的變量類型只能爲 byteshortintchar 或者 String
  • switch 語句可以擁有多個 case 語句。每個 case 後面跟一個要比較的值和冒號。
  • case 語句中的值的數據類型必須與變量的數據類型相同,而且只能是常量或者字面常量。
  • 當變量的值與 case 語句的值相等時,那麼 case 語句之後的語句開始執行,直到 break 語句出現纔會跳出 switch 語句。
  • 當遇到 break 語句時,switch 語句終止。程序跳轉到 switch 語句後面的語句執行。case 語句不必須要包含 break 語句。如果沒有 break 語句出現,程序會繼續執行下一條 case 語句,直到出現 break 語句。
  • switch 語句可以包含一個 default 分支,該分支必須是 switch 語句的最後一個分支。default 在沒有 case 語句的值和變量值相等的時候執行。default 分支不需要 break 語句。

語法

switch(expression){
    case value :
       //語句
       break; //可選
    case value :
       //語句
       break; //可選
    //你可以有任意數量的case語句
    default : //可選
       //語句
       break; //可選,但一般建議加上
}

示例

public class SwitchDemo {
    public static void main(String args[]) {
        char grade = 'C';

        switch (grade) {
        case 'A':
            System.out.println("Excellent!");
            break;
        case 'B':
        case 'C':
            System.out.println("Well done");
            break;
        case 'D':
            System.out.println("You passed");
        case 'F':
            System.out.println("Better try again");
            break;
        default:
            System.out.println("Invalid grade");
            break;
        }
        System.out.println("Your grade is "   grade);
    }
}
// output:
// Well done
// Your grade is C

2. 循環語句

2.1. while 循環

只要布爾表達式爲 truewhile 循環體會一直執行下去。

語法

while( 布爾表達式 ) {
    //循環內容
}

示例

public class WhileDemo {
    public static void main(String args[]) {
        int x = 10;
        while (x < 20) {
            System.out.print("value of x : "   x);
            x  ;
            System.out.print("\n");
        }
    }
}
// output:
// value of x : 10
// value of x : 11
// value of x : 12
// value of x : 13
// value of x : 14
// value of x : 15
// value of x : 16
// value of x : 17
// value of x : 18
// value of x : 19

2.2. do while 循環

對於 while 語句而言,如果不滿足條件,則不能進入循環。但有時候我們需要即使不滿足條件,也至少執行一次。

do while 循環和 while 循環相似,不同的是,do while 循環至少會執行一次。

語法

do {
    //代碼語句
} while (布爾表達式);

布爾表達式在循環體的後面,所以語句塊在檢測布爾表達式之前已經執行了。 如果布爾表達式的值爲 true,則語句塊一直執行,直到布爾表達式的值爲 false。

示例

public class DoWhileDemo {
    public static void main(String args[]) {
        int x = 10;

        do {
            System.out.print("value of x : "   x);
            x  ;
            System.out.print("\n");
        } while (x < 20);
    }
}
// output:
// value of x:10
// value of x:11
// value of x:12
// value of x:13
// value of x:14
// value of x:15
// value of x:16
// value of x:17
// value of x:18
// value of x:19

2.3. for 循環

雖然所有循環結構都可以用 while 或者 do while 表示,但 Java 提供了另一種語句 —— for 循環,使一些循環結構變得更加簡單。for 循環執行的次數是在執行前就確定的。

語法

for (初始化; 布爾表達式; 更新) {
    //代碼語句
}

  • 最先執行初始化步驟。可以聲明一種類型,但可初始化一個或多個循環控制變量,也可以是空語句。
  • 然後,檢測布爾表達式的值。如果爲 true,循環體被執行。如果爲 false,循環終止,開始執行循環體後面的語句。
  • 執行一次循環後,更新循環控制變量。
  • 再次檢測布爾表達式。循環執行上面的過程。

示例

public class ForDemo {
    public static void main(String args[]) {
        for (int x = 10; x < 20; x = x   1) {
            System.out.print("value of x : "   x);
            System.out.print("\n");
        }
    }
}
// output:
// value of x : 10
// value of x : 11
// value of x : 12
// value of x : 13
// value of x : 14
// value of x : 15
// value of x : 16
// value of x : 17
// value of x : 18
// value of x : 19

2.4. foreach 循環

Java5 引入了一種主要用於數組的增強型 for 循環。

語法

for (聲明語句 : 表達式) {
    //代碼句子
}

聲明語句:聲明新的局部變量,該變量的類型必須和數組元素的類型匹配。其作用域限定在循環語句塊,其值與此時數組元素的值相等。

表達式:表達式是要訪問的數組名,或者是返回值爲數組的方法。

示例

public class ForeachDemo {
    public static void main(String args[]) {
        int[] numbers = { 10, 20, 30, 40, 50 };

        for (int x : numbers) {
            System.out.print(x);
            System.out.print(",");
        }

        System.out.print("\n");
        String[] names = { "James", "Larry", "Tom", "Lacy" };

        for (String name : names) {
            System.out.print(name);
            System.out.print(",");
        }
    }
}
// output:
// 10,20,30,40,50,
// James,Larry,Tom,Lacy,

3. 中斷語句

3.1. break 關鍵字

break 主要用在循環語句或者 switch 語句中,用來跳出整個語句塊。

break 跳出最裏層的循環,並且繼續執行該循環下面的語句。

示例

public class BreakDemo {
    public static void main(String args[]) {
        int[] numbers = { 10, 20, 30, 40, 50 };

        for (int x : numbers) {
            if (x == 30) {
                break;
            }
            System.out.print(x);
            System.out.print("\n");
        }

        System.out.println("break 示例結束");
    }
}
// output:
// 10
// 20
// break 示例結束

3.2. continue 關鍵字

continue 適用於任何循環控制結構中。作用是讓程序立刻跳轉到下一次循環的迭代。在 for 循環中,continue 語句使程序立即跳轉到更新語句。在 while 或者 do while 循環中,程序立即跳轉到布爾表達式的判斷語句。

示例

public class ContinueDemo {
    public static void main(String args[]) {
        int[] numbers = { 10, 20, 30, 40, 50 };

        for (int x : numbers) {
            if (x == 30) {
                continue;
            }
            System.out.print(x);
            System.out.print("\n");
        }
    }
}
// output:
// 10
// 20
// 40
// 50

3.3. return 關鍵字

跳出整個函數體,函數體後面的部分不再執行。

示例

public class ReturnDemo {
    public static void main(String args[]) {
        int[] numbers = { 10, 20, 30, 40, 50 };

        for (int x : numbers) {
            if (x == 30) {
                return;
            }
            System.out.print(x);
            System.out.print("\n");
        }

        System.out.println("return 示例結束");
    }
}
// output:
// 10
// 20

🔔 注意:請仔細體會一下 returnbreak 的區別。

4. 最佳實踐

  • 選擇分支特別多的情況下,switch 語句優於 if...else if...else 語句。
  • switch 語句不要吝嗇使用 default
  • switch 語句中的 default 要放在最後。
  • foreach 循環優先於傳統的 for 循環
  • 不要循環遍歷容器元素,然後刪除特定元素。正確姿勢應該是遍歷容器的迭代器(Iterator),刪除元素。

5. 參考資料

發佈了182 篇原創文章 · 獲贊 32 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章