標籤:
1、順序結構 if語句
if(運算式){執行語句塊}(變數=布林運算式?語句1:語句2 運算式為真則執行語句1,反之執行語句2)
if(運算式){執行語句塊} else {}
if(運算式1){執行語句塊} else if(運算式2){}else
if語句也可以嵌套在if語句中,else與上文中最近的if匹配
2、選擇結構 switch語句
看著下面的代碼,也真是醉了,我咋能寫出這樣的~不過從中也可以吸取點教訓,case後面跟的只能是常量,switch後面的運算式可以接受byte、short、int、char型
1 public static void main(String agrs[]) 2 { 3 int grade=85; 4 switch(grade) 5 { 6 /*case(grade < 60)://報錯 不相容的類型: boolean無法轉換為int (case後面必須是常量) 7 System.out.println("You are unpassed!");*/ 8 case 1://傻帽!grade是85,肯定是不等於1啊,怎麼可能去執行if語句,最後輸出結果肯定是It‘s Wrong! 9 if(grade<60)10 System.out.println("You are unpassed!");11 case 2:12 if((grade>60)&&(grade<80))13 System.out.println("You got B!");14 case 3:15 if((grade>80)&&(grade<=100))16 System.out.println("You got A!");17 default:18 System.out.println("It‘s Wrong!");19 }20 }
再寫一個正確的
1 public static void main(String agrs[]) 2 { 3 int x=3; 4 switch(x) 5 { 6 case 1: 7 System.out.println("It‘s Monday"); 8 case 2: 9 System.out.println("It‘s Tuesday");10 case 3:11 System.out.println("It‘s Wednesday");12 case 4:13 System.out.println("It‘s Thursday");14 case 5:15 System.out.println("It‘s Friday");16 default:17 System.out.println("It‘s Weekend!");18 }19 }
輸出結果:
It‘s Wednesday
It‘s Thursday
It‘s Friday
It‘s Weekend!
說明switch中一旦碰到滿足條件的case,不僅執行完該case中的語句,還順序執行其後面的內容,為了避免這個問題,需要在每個case的語句後加上break跳出迴圈
1 public static void main(String agrs[]) 2 { 3 int x=3; 4 switch(x) 5 { 6 case 1: 7 System.out.println("It‘s Monday"); 8 case 2: 9 System.out.println("It‘s Tuesday");10 case 3:11 case 4:12 System.out.println("It‘s Thursday");13 break;14 case 5:15 System.out.println("It‘s Friday");16 default:17 System.out.println("It‘s Weekend!");18 }19 }//輸出It‘s Thursday
從上面代碼中可以看到,加了break就可以跳出迴圈,並且,還說明了一個問題,就是,當多種情況下要執行的語句是一樣的,我們可以如上所示操作,將3、4共用同一語句塊
3、迴圈語句
while(運算式){語句}//當運算式為真,則執行語句
do
{
語句
}while(運算式); //先執行語句,在執行while中的運算式,若為真,則繼續執行語句,直至運算式為假
for(初始設定式;迴圈條件運算式;迴圈後的動作表達式)迴圈體
break 跳出當前迴圈體
continue 跳出當前迴圈語句,接著執行下一次的迴圈
1 public static void main(String agrs[]) 2 { 3 int i=1; 4 for(;i<11;i++) 5 { 6 if(i%3==0) 7 break; 8 System.out.println(i); 9 }10 }//輸出1,2
1 public static void main(String agrs[]) 2 { 3 int i=1; 4 for(;i<11;i++) 5 { 6 if(i%3==0) 7 continue; 8 System.out.println(i); 9 }10 }//輸出1,2,4,5,7,8,10
ps:當break被標記,如下所示,執行完break st後,程式會跳出最外層while(即被標記的while迴圈),慎用~
st:while(true)
{
while(true)
{
break st;
}
}
Java基礎-學習筆記(四)-流程式控制制