Java控制流程

分支控制

    if/else語句

        雙分支:

           if(boolean表達式){
              //表達式爲true執行的語句1
           }else{
              //表達式爲false則執行語句2
           }

        多分支:

           if(boolean表達式1){
             //表達式1爲true執行的語句1
           }else if(boolean表達式2){
             //表達式2爲true執行的語句2
           }
            ........
           else{
              //以上所有的表達式均爲false則執行語句3
           }

    switch語句

        多分支                     

           switch(表達式){
           //表達式和以下常量表達式匹配,匹配上則執行對應的語句
              case 常量表達式1:語句1
              case 常量表達式2:語句2
              ......
              case 常量表達式n:語句n
              default: 語句n+1
           }

循環控制

    while           

           while(boolean表達式){ //表達式爲true則執行循環體
              //循環體
           }

    do while      

           do{
              //循環體
             //先執行一遍循環體的內容,再執行boolean表示式
              //執行完一遍循環體,判斷boolean表達式,爲true則繼續
              //否則退出循環
           }while(boolean表達式);

    for        

            for(表達式1;表達式2;表達式3){
              //表達式1爲: 循環的初始狀態 比如 int i =0;
              //表達式2爲: 確定循環的次數 比如數組的長度或者集合的大小
              //表達式3爲: 改變初始狀態 比如 i++; i 循環累加
              //循環體
            }

結合自己曾經的經驗,使用分支和循環的一個小技巧: 

簡單需求描述就是,實體類 Person類,字段name,age,address,集合List<List<String>>,集合中的集合內容爲Person類的屬性值,比如內層List<String> 第一個集合內容 Tom, 18, New York,現在需要把內層List<String>裝載成Person對象,整個集合就成了List<Person>

外層List用list表示,內層用listN表示,

    List<Person> persons = new ArrayList<Person>();  //最終的結果集合      
    for (int i = 0; i < list.size; i++) {
      list1 = list.get(i);
       person = new Person(); 
      for(int j = 0; j < listN.size; j++){          
        switch(j)
        case 1: person.setName(list1.get(j));
        case 2: person.setAge(list1.get(j));
        case 3: person.setAddress(list1.get(j));
        persons.add(person);//把對象裝載進集合
      }      
    }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章