Java basic | Java OOP | โครงสร้างข้อมูล | โจทย์ ACM



[Java]การใช้ for-each

No comments


             นอกเหนือจากการใช้ For loop แบบมี ค่าเริ่ม;เงื่อนไข;เพิ่มค่า ยังมีการวนลูปอีกแบบหนึ่งในภาษา Java คือ for - each  loop โดยมีรูปแบบคำสั่งดังนี้

                         for(declaration : expression) {
                               statement
                         }

                - declaration : เป็นการประกาศตัวแปรทั่วไป เช่น String color
                - expression : จะเป็นอาร์เรย์ (array) หรือ Object
                - statement : อาจจะเป็น การคำนวน การแสดงค่า(print)

              แล้วมันต่างจาก for ธรรมดาอย่างไร ข้อดีของ for-each คือกรณีที่เราต้องการโชว์ข้อมูลใน Array ทั้งหมด for -each จะทำได้ง่ายกว่า อาจจะมองภาพยังไม่ออกลองดูตัวอย่างโค้ดด้านล่าง

               /*
                * การใช้งาน foreach
                * @author http://javaagkasit.blogspot.com/
                */
                  public class foreach {
                         public static void main(String [] args){
     
                         String [] colors = {"Red","Blue","Pink","Yellow","Orange"};
                         //for ธรรมดา
                         for(int i =0 ; i< colors.length ;i++){
                                  System.out.println(colors[i]);
                         }
                         //for -each 
                         for(String c : colors){
                                 System.out.println(c);
                         }
                    }
              }

              จากโค้ดด้านบน จะเห็นได้ว่าการใช้ for-each จะทำได้ง่ายและเร็วกว่าการใช้ for ธรรมดา แต่ในทางกลับกันในความสะดวกสะบายของ for - each ยังมีข้อเสียอยู่ ในกรณี ถ้าเราต้องการแสดงเฉพาะตำแหน่งเราต้องการโชว์ เช่น โชว์เฉพาะตำแหน่ง colors[0]  จะทำไม่ได้


เนื่้อหาที่เกี่ยวข้อง
        - การใช้ for http://javaagkasit.blogspot.com/2012/08/for.html
        - การใช้ switch casehttp://javaagkasit.blogspot.com/2012/08/switch-case.html
        - การใช้ if else http://javaagkasit.blogspot.com/2012/08/if-else.html
        - การใช้ if else if http://javaagkasit.blogspot.com/2012/08/if-else-if.html

share

No comments :

Post a Comment