標籤:2-2 文法 public 使用 邏輯 exti 表示 col ...
迴圈結構
當需要重複執行相同的代碼或者是相似的代碼時,就要用到迴圈結構了。
迴圈三要素:
(1)迴圈變數的聲明:用於控制迴圈次數的迴圈因子
(2)迴圈條件:用於判斷是否執行相同或相似內容(迴圈體)的條件
(3)迴圈變數的改變方向:向著迴圈結束的方向改變。、
(1)for迴圈:
文法:
for(變數的聲明和初始化;迴圈條件;變數的改變方向){
迴圈體;
}
執行邏輯:
程式遇到for時,一定執行變數的聲明和初始化,然後執行迴圈條件進行判斷,如果為false,會跳過迴圈結構,執行後續代碼。如果為true,執行迴圈體,然後再執行變數的改變,再執行迴圈條件的判斷,.......
迴圈體:是要重複執行的相同或相似邏輯
break關鍵字:用在迴圈結構中時,表示結束/打斷迴圈
continue關鍵字:用在迴圈結構中,表示結束當次迴圈體,繼續下一次迴圈
雙層for迴圈:
for迴圈中有嵌套了一個for迴圈,外層變數執行一次,內層變數執行一遍或外層變數控制行數,內層變數控制列數
練習代碼:
public static void main(String[] args) { //列印一個空心等腰三角形 int n=6; for(int i=0;i<n;i++){ for(int j=i;j<n;j++){ System.out.print(" "); } System.out.print("*"); if(i!=n-1){ for(int x=i*2-1;x>0;x--){ System.out.print(" "); } if(i!=0){ System.out.print("*"); } }else{ for(int k=0;k<(n*2-2);k++){ System.out.print("*"); } } System.out.println(); } }(2)while迴圈
文法:
while(迴圈條件){
迴圈體
}
執行邏輯:
當程式遇到while時,一定執行迴圈條件,如果判斷結果為false,就結束迴圈結構,執行後續代碼,如果判斷結果為true,就執行迴圈體,然後再判斷迴圈條件......
練習代碼:
public static void main(String[] args){ /*列印十次 hello world*/ int count = 1; while(count<=10){ System.out.println("hello world"); count++; } /* 第二種常用寫法 */ int num = 1; while(true){ System.out.println("hello world"); num++; if(num>10){ break; } } }(3)do-while迴圈
文法:
do{
迴圈體
}while(迴圈條件);
執行邏輯:當程式遇到do關鍵字時,一定先執行一次迴圈體,然後再判斷迴圈條件,如果條件為false,結束迴圈結構,執行後續代碼,如果條件為true,再執行一次迴圈體,然後再判斷條件的成立與否........
while/do-while/for的區別:
while/do-while:適合不知道迴圈次數的邏輯
for:適合知道迴圈次數的邏輯
while/for一般先判斷條件,再執行迴圈體
do-while:一定先執行一次迴圈體,再判斷條件
提示:什麼時候使用while,什麼時候使用do-while某些邏輯可以翻譯成如下:
當......就執行.....:適合使用while
做.....直到.......:適合使用do-while
練習代碼:
public static void main(String[] args){ /*銀行卡密碼為 888888 使用do-while類比ATM輸入密碼操作 */ Scanner sc = new Scanner(System.in); int input = -1; do{ System.out.println("請輸入密碼:"); input = sc.nextInt(); }while(input!=888888); System.out.println("密碼驗證成功"); }
JAVA基礎(5)-迴圈語句