title: Java基礎語法(4)-流程控制 html
blog: CSDNjava
data: Java學習路線及視頻spring
//正確形式 public class Test{ int num1 = 12; int num2 = num1 + 2; } //錯誤形式 public class Test{ int num2 = num1 + 2; int num1 = 12; }
if(條件表達式){ 執行代碼塊; }
if(條件表達式){ 執行代碼塊1; } else{ 執行代碼塊2; }
if(條件表達式1){ 執行代碼塊1; } else if (條件表達式2){ 執行代碼塊2; } …… else{ 執行代碼塊n; }
分支結構:if-else使用說明後端
if-else語句應用舉例springboot
public class AgeTest{ public static void main(String args[]){ int age = 15; if (age< 0) { System.out.println("不可能!"); } else if (age>250) { System.out.println("是個妖怪!"); } else { System.out.println(「人家芳齡 " + age +" ,馬馬乎乎啦!"); } } }
switch(表達式){ case 常量1: 語句1; // break; case 常量2: 語句2; // break; … … case 常量N: 語句N; // break; default: 語句; // break; }
public class SwitchTest { public static void main(String args[]) { int i = 1; switch (i) { case 0: System.out.println("zero"); break; case 1: System.out.println("one"); break; default: System.out.println("default"); break; } } }
若是判斷的具體數值很少,並且符合byte、short 、char、int、String、枚舉等幾種類型。雖然兩個語句均可以使用,建議使用swtich語句。由於效率稍高。架構
其餘狀況:對區間判斷,對結果爲boolean類型判斷,使用if,if的使用範圍更廣。也就是說,使用switch-case的,均可以改寫爲if-else。反之不成立。前後端分離
在某些條件知足的狀況下,反覆執行特定代碼的功能oop
循環語句的四個組成部分學習
初始化部分(init_statement).net
循環體部分(body_statement)
for (1.初始化部分;2.循環條件部分;3.迭代部分){ 4.循環體部分; }
public class ForLoop { public static void main(String args[]) { int result = 0; for (int i = 1; i <= 100; i++) { result += i; } System.out.println("result=" + result); } }
①初始化部分 while(②循環條件部分){ ③循環體部分; ④迭代部分; }
①-②-③-④-②-③-④-②-③-④-...-②
public class WhileLoop { public static void main(String args[]) { int result = 0; int i = 1; while (i <= 100) { result += i; i++; } System.out.println("result=" + result); } }
①初始化部分 do{ ③循環體部分; ④迭代部分; }while(②循環條件部分);
①-③-④-②-③-④-②-③-④-...-②
public class DoWhileLoop { public static void main(String args[]) { int result = 0, i = 1; do { result += i; i++; } while (i <= 100); System.out.println("result=" + result); } }
2020-3-27: Java基礎語法(2)-變量
2020-3-27: Java基礎語法(3)-運算符
今日好文推薦
今日資料推薦