天天看點

Java 筆記(2)流程控制語句

流程控制語句

          • 順序結構
          • 選擇結構
          • 循環結構
          • break 和 continue
          • 遞歸
順序結構
“順序結構”代表“先執行a,再執行b”的邏輯。
           
選擇結構
“選擇結構”代表“如果…,則…”的邏輯。比如,如果看到紅燈,則停車;
           
  • if 單選擇結構
if(條件){
	執行語句塊
	}
           
  • if - else 雙選擇結構
if(條件){
	執行語句塊1
	}else{
	執行語句塊2
	}
           
  • if - else if - else 多選擇結構
public class Test{
	public static void main(String[] args) {
        int result = (int) (100 * Math.random());  //随機生成一百以内的數
        System.out.print("成績是" + result + ", 等級為");
        if (result < 60) {
            System.out.println("D");
        } else if (result < 70) {
            System.out.println("C");
        } else if (result < 90) {
            System.out.println("B");
        } else {
            System.out.println("A");
        }
    }
}
           
  • switch結構
public class Test{
	public static void main(String[] args) {
        int result = (int) (100 * Math.random());
        System.out.print("成績是" + result + ", 等級為");
        switch(result/10){
       		case 1:
       		case 2:
       		case 3:
       		case 4:
       		case 5:
       			System.out.println("D");
       			break;
       		case 6:
       		case 7:
       			System.out.println("C");
       			break;
       		case 8:
       			System.out.println("B");
       			break;
       		case 9:
       		case 10:
       			System.out.println("A");
   				break;
		}
    }
}
           
循環結構
“循環結構”代表“如果…,則再繼續…”的邏輯。比如,如果沒找到喜歡的人,則再繼續找。
           
  • for
for (初始表達式; 布爾表達式; 疊代因子) {
      循環體;
}
           
  • while 當條件表達式為True時反複執行{}内語句,直到不滿足條件
while(布爾表達式){
	...
	}
           
  • do - while 先執行一遍語句再判斷條件
do {
	...
     } while(布爾表達式) ;
           

while與do-while的差別,在布爾表達式的值為false時while的循環體一次也不執行,而do-while至少執行一次

public class Test {
    public static void main(String args[]) {
		//for嵌套循環實作九九乘法表
        for (int i = 1; i < 10; i++) { // i是一個乘數
            for (int j = 1; j <= i; j++) { // j是另一個乘數
                System.out.print(j + "*" + i + "=" + (i * j < 10 ? (" " + i * j) : i * j) + "  ");
            }
            System.out.println();
        }
    }
}
           
Java 筆記(2)流程控制語句
break 和 continue
  • break 結束循環
  • continue 跳過目前循環,執行下一循環
遞歸
  • 基本思想:“自己調用自己”
  • 優點:簡單的程式解決複雜問題
  • 缺點:既耗時間又号記憶體
  • 遞歸結構
    • 遞歸頭——遞歸結束的條件,無則陷入死循環
    • 遞歸體——什麼時候需要調用自身方法
/*遞歸:計算n!*/
public class Test {
    public static void main(String[] args) {
        long d1 = System.currentTimeMillis(); 		 //記錄遞歸前時間
        System.out.printf("%d階乘的結果:%s%n", 10, factorial(10));
        long d2 = System.currentTimeMillis(); 		 //記錄遞歸後時間
        System.out.printf("遞歸費時:%s%n", d2-d1);  //計算耗時
    }
    /** 求階乘的方法*/
    static long  factorial(int n){
        if(n==1){//遞歸頭
            return 1;
        }else{//遞歸體
            return n*factorial(n-1);//n! = n * (n-1)!
        }
    }
}
           

深入了解遞歸點選跳轉