iT邦幫忙

0

重新學JAVA-01-2 if-for-while-switch

  • 分享至 

  • xImage
  •  

If陳述式

根據條件判斷執行不同的程式區塊,讓程式能夠根據不同的狀況執行不同的邏輯
if(condition){
    //when codition is true, program will do this area
}

if(condition){
    //when codition is true, program will do this area
}else {
    //when codition is false, program will do this area
}

if(condition_1){
    //when codition_1 is true, program will do this area
}else if(condition_2){
    //when codition_2 is false, program will do this area
}else{
    //所有條件都不為真執行這段區塊
}

sample
int age = 31;
if(age >= 21){
    System.out.println("you are a adult");
}else if(age >= 18){
    System.out.println("you are a young adult");
}else{
    System.out.println("you are too smaller");
}

int coin = 50;
if(coin >= 10){
    System.out.println("you are very rich");
}else if(coin >=3){
    System.out.println("you are a normal");
}else{
    System.out.println("you are poor");
}    

loop-for

迴圈for由3個部分組成
    初始話語句 :定義迴圈變數
    條件語句   :當條件為true時繼續執行迴圈
    更新語句   :每次迴圈執行後更新變數

for(初始化語句; condition; update){
    //每次迴圈執行的程式碼
}

sample
for(int i = 0; i <=5; i++){
    System.out.println(i);
}

loop-while

迴圈while 用來執行一段重複的程式碼,直到條件不再滿足為止,在處理不確定次數的程式時,也是一種好方法。
不過在寫while的時候要特別注意條件語句的撰寫,因為當條件一直為真時,程式就會一直重複執行,而無法結束,這個現象就是俗稱的"無窮迴圈",這會使電腦當機。因此在寫while的時候要特別注意條件語句。

sample
while(int i<=10){
    System.out.println(i);
    i++; //加入這段條件,增加i的值,這是用來防止進入無權迴圈
        //不過也可以使用 break 讓程式在執行完個某條件之後就結束
}

while(true){
    System.out.println("this is will print forever!);
}
 

條件判斷-switch

通常用來代替多重if-else判斷,想成一個比較複雜的if-else。用來處理不同條件不同區塊的程式碼,需要判斷條件是較為簡單且多個選項時,使用switch是個不錯的選擇

expression-要被檢查的值,可能是字串、變數類型、變數、或其他可以等於常數的類別
case vaule-為每個可能的值,當expression等於這個值的時候,對應的程式區域會執行
break-用來跳出switch陳述式,防止後面的case value也執行,若是省略break,則下面的case value也會被執行(fail-through)
default-當所有case都不符合時,default就會執行

sample
int day = 3;
switch(day){
    case 1:
        System.out.println("monday");
        break;
    case 2:
        System.out.println("tuesday");
        break;
    case 3:
        System.out.println("wenesday");
        break;
    default
        System.out.println("invaild day");
 }       
 //輸出    wenesday    
      

int number = 2;
switch(number){
    case 1:
        System.out.println("1");
    case 2:
        System.out.println("2");
    case 3:
        System.out.println("3");
    default
        System.out.println("default");
 }       
 //輸出    2 3 default
 //原因 case 2的敘述內沒有break
        

圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言