บทที่ 3

 โครงสร้างการควบคุมโปรแกรม

(Control Structures)


หัวข้อ (Topic):

3.1  กลุ่มคำสั่งตัดสินใจเลือกทำ (Selection)

3.2  กลุ่มคำสั่งในการทำซ้ำ (Repetition)

 

วัตถุประสงค์การเรียนรู้ (Learning Objective):

1.             บอกความแตกต่างของการใช้กลุ่มคำสั่ง  Selection และกลุ่มคำสั่ง Iterative ได้

2.             สามารถเขียนและอธิบาย Syntax ของกลุ่มคำสั่ง  Selection และกลุ่มคำสั่ง Iterative ได้

3.             สามารถใช้คำสั่ง Break  และ Continue  ได้อย่างถูกต้อง

4.             สามารถเขียนโปรแกรมโดยใช้ชุดคำสั่งของ  Selection กับ  Iterative ได้

 

โครงสร้างการควบคุมโปรแกรมหรือ ประโยคคำสั่งในการควบคุมโปรแกรม

(Control  Structure)  เป็นสิ่งที่จำเป็นเสมอสำหรับภาษาเขียนโปรแกรมทุก ๆ ภาษาเพียงแต่ในแต่ละภาษาจะมี Syntax การใช้งานที่แตกต่างกันบ้างเล็กน้อย ดังนั้นหากคุณมีความแม่นยำในรูปแบบหรือ Syntax การใช้งาน  ก็จะทำให้การเขียนโปรแกรมนั้นดูง่ายขึ้นและลดข้อผิดพลาดของการเขียน Code ได้

 

3.1  กลุ่มคำสั่งตัดสินใจเลือกทำ (Selection)

              กลุ่มคำสั่งในการเลือกทำ (Selection)  หรือบางภาษาอาจใช้คำว่า  กลุ่มคำสั่งในการตัดสินใจเลือกทำงาน (Decision)  ซึ่งลักษณะการทำงานของกลุ่มคำสั่งเหล่านี้  ต้องอาศัยการเปรียบเทียบเงื่อนไขเพื่อตัดสินใจ ผลลัพธ์ของการเปรียบเทียบจะได้ค่าจริงกับเท็จ  (True / False) โดยใช้เครื่องหมายในการเปรียบเทียบค่า (Comparison Operator) เข้ามาใช้ร่วมด้วย  (ดูบทที่ 2)  ซึ่งกลุ่มคำสั่งในการตัดสินใจเลือกทำ   จะสามารถจำแนกคำสั่งออกเป็น 2 กลุ่ม ได้แก่ การใช้ IF  และ  Switch..Case

 

 

 

 

3.1.1  การใช้  If

If  แปลว่า  “ ถ้า”    ดังนั้นฟังจากชื่อแล้วคำสั่งนี้จะทำงานได้ต้องอาศัยการเปรียบเทียบ

เงื่อนไขจริงและเท็จก่อนทุกครั้ง  โดยเราสามารถจำแนกรูปแบบการใช้ if  ออกเป็น 3  รูปแบบ ได้แก่ if,   if..else  และ  else..if

 

-  การใช้ if  โดยปราศจาก else

                        หมายถึงจะทำงานเมื่อเงื่อนไขเป็นจริงเท่านั้น

Syntax:

if (condition)

  {

      statement;

      statement;

}  ßกรณีที่ Body ของ if มีเพียง Statement เดียวไม่จำเป็นต้องใช้เครื่อง  {   }  ครอบหรือก็ได้

 

 
 

                       

 

 

 

 

 

 

Note:  เห็นได้ว่า Syntax  การใช้ if ในภาษา Java นั้น  หลัง if  ไม่มีคำว่า Then  และไม่ต้องจบ if ด้วยคำว่า “end  if”   ดังนั้นถ้าคุณมีความคุ้นเคยกับ Syntax ของภาษาอื่นก็ต้อง  ก็ต้องปรับความคุ้นเคยกันสักนิด

 

ตัวอย่างโปรแกรม : ถ้าค่าของตัวแปรหารด้วย  2 แล้วได้เศษเท่ากับศูนย์ ให้ทำงานในส่วนของ if

Output

The number is even

 

Source Code:

1         //Progif.java                                          

2         public class Progif {                           

3         public static void main (String agrs[])

4         {                                                              

5         int i = 10;                                               

6         if (i %2==0)                                        

7           System.out.println ("The number is even");

8              }  //end main()                               

9         } //end class                                           

 

-  การใช้   if..else 

  จะทำงานในส่วนของ if  เมื่อเงื่อนไขเป็นจริง  และทำงานในส่วนของ else  เมื่อ

เงื่อนไขเป็นเท็จ

 

Syntax:

                      if (condition)

                      {

                                statement;

                                statement;

                      }

                        else

                      {

                                statement;

                                statement;

                      } 

 

 

 

ตัวอย่างโปรแกรม : ถ้าค่าของตัวแปรหารด้วย  2 แล้วได้เศษเท่ากับศูนย์ ให้ทำงานในส่วนของ if  แต่ถ้าไม่ใช่ให้ไปทำงานในส่วนของ else

Output

The number is odd

 

Source Code:

1         //Progif1.java                                        

2         public class Progif1{                          

3         public static void main (String agrs[])

4         {                                                              

5         int i = 13;                                               

6         if (i %2==0)                                        

7           System.out.println ("The number is even");

8         else                                                          

9           System.out.println ("The number is odd");

10            } //end main()                                

11       } //end class                      

 

ตัวอย่างโปรแกรม : การใช้ if  และ  else  กับข้อมูลอักขระ

Output:

The character is range A or B

 

Source Code:

1         //Programor.java                                       

2         public class Programor  {                       

3         public static void main (String agrs[])

4         {                                                                   

5         char a = 'B';                                                

6         if ((a == 'A') || (a == 'B'))  ß เงื่อนไข OR     

7           System.out.println ("The character is range A or B");

8         else                                                               

9           System.out.println ("Out of range");

10            }                                                              

11       }                                                                     

 

-  การใช้  else..if

เราจะใช้ els..if  เมื่อต้องการตรวจสอบเงื่อนไข  มากกว่า 1 เงื่อนไข

 

Syntax:

                    if (condition)

                      {statement;

                         statement;}

                    else if  (condition)

                      { statement;

                          statement;}

                      else if  (condition)

                      { statement;

                         statement;}

                      else

                      { statement;

                         statement;}

 

ตัวอย่างโปรแกรม : การใช้  else..if  กับเงื่อนไข AND

Output:

Value between 0-9

 

Source Code:

1         //Progif2.java                                                              

2         public class Progif2  {                                             

3         public static void main (String agrs[])               

4         {                                                                                    

5         int i = 8;                                                                       

6         if ((i  >= 0) && (i <= 9))                                     

7         {  System.out.println ("Value between 0-9");}

8         else if ((i >= 10) && (i <=19))                           

9           {System.out.println ("Value between 10-19");}

10       else if ((i >= 20) && (i <=29))                            

11       {  System.out.println ("Value between 20-29");}

12       else                                                                                 

13           System.out.println ("Out  of  range");           

14            }                                                                               

15       }                                                                                     

 

ตัวอย่างโปรแกรม : การใช้ if ซ้อน if

Output:

mark 70-74   Grade = B

 

Source Code:

1         //Progif3.java                                                                                                                                                

2         public class Progif3  {                                                                                                                                       

3         public static void main (String agrs[])                                                                                                 

4         {                                                                                                                                                                      

5         int i = 72 ;                                                                                                                                                     

6         if ((i  >= 80) && (i <=100))                                                                                                                 

7         {  System.out.println ("mark 80-100   Grade = A ");}                                                                    

8         else                                                                                                                                                                 

9                                        if  ((i >= 75) && (i <=79))                                                                                       

10                                                     {System.out.println ("mark 75-79   Grade = B+");}                          

11                                      else                                                                                                                                    

12                                                  if ((i >= 70) && (i <=74))                                                                           

13                                                                       {  System.out.println ("mark 70-74   Grade = B");}        

14                                                  else                                                                                                                        

15                                                  System.out.println ("please coding to continue..not complete");

16            }                                                                                                                                                                 

17       }                                                                                                                                                                       

 

ตัวอย่างโปรแกรม : การเขียน Statement ของ if และ else ให้สั้นลง

Output:

The number is odd

 

Source Code:

1         //Pcut.java                                                                     

2         public class Pcut {                                                      

3         public static void main (String agrs[])                

4         {                                                                                     

5         int i = 9;                                                                        

6         if (i %2==0)   System.out.println ("The number is even");

7         else System.out.println ("The number is odd");

8              }                                                                                

9         }                                                                                       

 

3.1.2  การใช้ switch..case

                                switch..case  นั้นจะใช้กับการตัดสินใจที่มีขนาดไหญ่ขึ้นหรือมีเงื่อนไขหลายระดับชั้นมากขึ้น  แต่จะทำให้คุณนั้นเขียน Code ได้กระชับและสั้นลง  มักนิยมนำ switch..case มาใช้ในการสร้าง Menu

 

 

 

 

Syntax :

switch (variable)  ß จะใช้ตัวแปรชนิด int และ  char

                { case constant 1 : statement;

                                                   statement;

                                                   break;

  case constant 2 : statement;

   statement;

                                                   break;

                   ………

                   ………

                case constant N : statement;

                                                statement;

                                                break;

                                default : statement;

                }  // จบ case

 

ตัวอย่างโปรแกรม : การใช้ตัวแปรชนิด int กับ switch..case

Output:

 

 

ch3_01

 

Source Code:

1        //Pswitch.java                                                          

2        public class Pswitch  {                                          

3        public static void main (String agrs[])           

4        {                                                                                

5        int a = 1;                                                                   

6        System.out.println ("==================");

7        System.out.println ("   Main Menu   ");        

8        System.out.println ("=================");

9        System.out.println ("1. Java                  "); 

10      System.out.println ("2. Visual C++     ");     

11      System.out.println ("3. C#                       "); 

12      System.out.println ("=================");

13      switch (a)                                                                 

14      {                                                                                  

15        case 1 :   System.out.println ("Choose Java");

16                               break;                                                

17        case 2 :   System.out.println ("Choose Visual C++");

18                               break;                                                

19        case 3 :   System.out.println ("Choose C#");

20                               break;                                                

21         default :  System.out.println ("Out of  Range");

22           } //end switch..case                                         

23      } //end main()                                                         

24      }//end class                                                               

 

 

 

 

3.2  กลุ่มคำสั่งในการทำซ้ำ (Repetition)

กลุ่มคำสั่งในการทำซ้ำ (Repetition)  หรือ  กลุ่มคำสั่งในการวนรอบการทำงาน (Loop)   ซึ่ง

กลุ่มคำสั่งเหล่านี้จะทำซ้ำ (วน Loop)  เมื่อเงื่อนไขเป็นจริง (True)   สามารถจำแนกการใช้ Repetition  ได้ 3  ประเภท ดังนี้

 

3.2.1  การใช้  for

ลูป for  ใช้เมื่อทราบจำนวนครั้งของการทำซ้ำที่แน่นอน  ซึ่งลูป for จัดเป็นลูปที่ใช้งานง่าย 

และพบบ่อยที่สุด  รูปแบบของ  for    ประกอบด้วย 3 นิพจน์   ดัง Syntax ด้านล่างนี้

 

Syntax:

for (นิพจน์กำหนดค่าเริ่มต้น; นิพจน์เปรียบเทียบค่า; นิพจน์เพิ่มค่า/ลดค่า)

                                                 { statement;

    statement;}

 

 

ตัวอย่างโปรแกรม :  การทำงานวนรอบด้วยลูป for

Output:

ch3_06

 

Source Code:

1        //Pfor.java                                                                    

2        public class Pfor  {                                                    

3        public static void main (String agrs[])               

4        {                                                                                    

5        int a,r=0;                                                                      

6        for (a=0;a<10;a++)                                                   

7        {                                                                                    

8          System.out.println ("Value of  round # "+r+" =  "+a);

9          a++;                                                                             

10        r++;                                                                             

11           }  //end  loop                                                        

12      } // end  main()                                                          

13      } //end  class                                                               

 

ตัวอย่างโปรแกรม :  สร้างสูตรคูณแม่ 2-12 โดยใช้ลูป for (เฉลย Multiply.java) 

Output:

 

 

ch3_07

Source Code:

1        //Multiply.java                                                                                                                        

2        public class Multiply{                                                                                                            

3        public static void main(String agrs[])                                                                               

4        {                                                                                                                                                   

5        int c;                                                                                                                                            

6        for (int a= 2;a<=12;a++ ) //แม่สูตรคูณ 2-12

7           {  for (int b=1;b<=12 ;b++ ) // ลำดับการคูณ 1-12                                                    

8                  {  c= a*b;                                                     

9                                              System.out.print("   "+c+"   "); 

10               } //end  inside  for                                    

11      System.out.print(" \n ");                                                                                                       

12           }  //end outside for                                                                                                           

13      }//end main()                                                                                                                            

  14         } //end class        

 

ตัวอย่างโปรแกรม :

Output:

 

ch3_11

Source Code:

1           // ForDL.java                                                                                                                   

2           import java.awt.Graphics;                                                                                            

3           import javax.swing.JApplet;                                                                                        

4                                                                                                                                                        

5           public class ForDL extends JApplet {                                                                      

6              public void paint( Graphics g )                   // draw lines on applet’s background

7              {                                                                                                                                       

8                 super.paint( g );                                             // call inherited version of method paint

9                 for ( int  line = 1; line <= 15; line++ )                  // 15 line                            

10                 g.drawLine( 10, 10, 250, line * 10 );                                                           

11                                                                                                                                                     

12           }  // end method paint                                                                                               

13        }  // end class                                                                                                                   

 

เมื่อคุณสร้าง File (.java)  และ Compile ผ่านเรียบร้อยแล้ว  และโปรแกรมนี้เป็น  Java Applet  ดังนั้นจงอย่าลืมว่าคุณยังต้องไปสร้าง File เอกสาร HTML แล้วฝัง File (.class) ที่ได้ลงไปจากนั้น Run ดูผลลัพธ์โดยใช้ IE Browser

 

                3.2.2  การใช้   do..while

 การใช้ do..while  นั้น  จะใช้เมื่อเราต้องการเข้าสู่การทำงานของลูป (Loop) อย่างน้อย 1

ครั้ง โดยจะวางนิพจน์ทดสอบค่าไว้ตอนท้ายของ Loop

 

Syntax :

 

do

                { statement;

   statement;}

while (condition);  ßอย่าลืมใส่เครื่องหมาย (  ;  )   หลังเงื่อนไข while  ไม่เช่นนั้นโปรแกรมจะค้าง (hang)

 

 

ตัวอย่างโปรแกรม :   ให้ทำงานในลูป do..while 6  รอบแล้วแสดงค่าตัวเลขตัวสุดท้าย

Output

h3_04

Source Code:

1         //Pdowhile.java                                                                                                                            

2         public class Pdowhile{                                                                                                               

3         public static void main (String agrs[])

4         {                                                                                                                                                      

5         int a=0,b=0,count=0;                                                                                                                  

6                                                                                                                                                                   

7         do {    //เข้าสู่ loop อย่างน้อย 1 ครั้ง

8                                                            a += 1;                                                                                        

9                                                             b += a;                                                                                        

10                                                           count++;                                                                                     

11                                                          System.out.println ("value b in loop  =     "+b);

12                 }                                                                                                                                          

13       while (a <= 5);  // ตรวจสอบเงื่อนไข  เป็นเท็จ จบ loop

14         System.out.println ("=======================");

15         System.out.println ("The round of  loop  =  "+count);

16         System.out.println ("last value b  =     "+b);

17            } //end main                                                                                                                                

18       } //end  class

 

ตัวอย่างโปรแกรม :รับค่าอายุ  หรือ ปี ค.ศ. ที่เกิด แล้วคำนวณหาอายุ หรือคำนวณว่าเกิดปี ค.ศ.    

ใดหลังจากนั้น  ถาม User  ว่าต้องการทำงานอีกรอบหรือไม่    ถ้าต้องการทำ กดเลข  1

Output:

 

 

 

Source Code:

1        // Ans2.java                                                                                   

2        import javax.swing.JOptionPane;                                           

3                                                                                                                  

4        public class Ans2 {                                                                     

5        public static void main( String args[] )                                

6        {                                                                                                       

7                int mul=1,                                                                       

8                   check=0,a;                                                                      

9               String  i,b;                                                                            

10      do                                                                                                     

11      {                                                                                                      

12              i = JOptionPane.showInputDialog(                             

13                  "Please Enter  Year  Age : " );                                

14            check = Integer.parseInt(i);                                              

15               mul  = 2006- check;                                                       

16                                                                                                         

17            JOptionPane.showMessageDialog( null,                       

18               "Result (Age/Birth Year) =  " + mul, " ",                

19               JOptionPane.INFORMATION_MESSAGE );       

20           // System.exit( 0 );                                                              

21                                                                                                               

22      b = JOptionPane.showInputDialog(                                      

23                  "Do you want to Continue. If say yes  Press 1 : " );

24      a = Integer.parseInt(b);                                                              

25      }                                                                                                       

26      while ( a == 1);  //end do..while                                             

27      System.exit( 0 );                                                                          

28      } //end main()                                                                               

29      }  // end class Ans2                                                                     

 

ตัวอย่างโปรแกรม :  การใช้ do..while  สร้างรูปวงกลมใน Java Applet

Output:

ch3_12

Source Code:

1           // DWhile.java                                                                                                      

2           import java.awt.Graphics;                                                                                

3                                                                                                                                            

4           import javax.swing.JApplet;                                                                            

5           public class DWhile extends JApplet {                                                         

6              public void paint( Graphics g )    // draw lines on applet’s background

7              {                                                                                                                           

8                                                                                                                                            

9                 super.paint( g );             // call inherited version of method paint 

10              int ov = 1;                                                                                                     

11              do {                                                                                                                 

12                 g.drawOval( 320 - ov * 40, 320 - ov * 40,                                     

13                    ov * 40, ov * 40 );                                                                              

14                 ++ov;                                                                                                          

15              } while ( ov <= 5 );  // end do...while                                                  

16                                                                                                                                          

17        ov=1;                                                                                                                      

18              do {                                                                                                                 

19                 g.drawOval( 110 - ov * 10, 110 - ov * 10,                                     

20                    ov * 20, ov * 20 );                                                                              

21                ++ov;                                                                                                          

22              } while ( ov <= 10 );  // end do...while                                               

23           }  // end method paint                                                                                    

24        }  // end class DoWhileTest                                                                             

 

                                Run   โดยใช้  IE Browser

 

 

3.2.3  การใช้   while

ลูป while  จะทำการตรวจสอบเงื่อนไขก่อน   หากพบว่าเงื่อนไขเป็นเท็จจะไม่เข้าไปทำ 

Statement ภายในลูป 

 

Syntax :

while (condition) ßจะต้องประกาศและกำหนดค่าของตัวแปร  ก่อนที่จะตรวจสอบเงื่อนไข                               

                {statement;

  statement;}

 

 

 

 

 

ตัวอย่างโปรแกรม : การกำหนดค่าคงที่กับลูป while

Output:

9

10

11

12

13

14

Finish loop and number of count   6

 

Source Code:

1         //Pwhile.java                                                                                        

2         public class Pwhile  {                                                                        

3         public static void main (String agrs[])                                        

4         {                                                                                                             

5         int i = 9 ;                                                                                               

6         int count = 0;                                                                                       

7         while (i != 15)                                                                // เงื่อนไขเป็นจริง  จะเข้าสู่ loop                         

8               {   System.out.println (i);                                                        

9                                     i++;                                                                             

10                                   count++;                                                                    

11                       } //end while                                                                   

12         System.out.println ("Finish loop and number of count   "+count);

13         System.exit(0);

14            } //end main()                                                                                

15       } //end class                                                                                             

 

 

 

ตัวอย่างโปรแกรม : การใช้ลูป while รับค่าคะแนนโดยใช้ JOptionPane  แล้วคำนวณหาค่าเฉลี่ย

Output:

 

ch3_02

Source Code:

1        // Average1.java                                                                                                                                            

2        import javax.swing.JOptionPane;                                                                                                            

3                                                                                                                                                                                   

4        public class Average1 {                                                                                                                              

5           public static void main( String args[] )                                                                                              

6           {                                                                                                                                                                     

7              int total,          // sum of grades input by user                                                                             

8                  gradeCounter,   // number of grades entered                                                                           

9                  gradeValue,     // grade value                                                                                                       

10                average;        // average of all grades                                                                                        

11            String grade;       // grade typed by user                                                                                        

12                                                                                                                                                                                

13            // Initialization Phase                                                                                                                           

14            total = 0;          // clear total                                                                                                              

15            gradeCounter = 1;   // prepare to loop                                                                                            

16                                                                                                                                                                                

17            // Processing Phase                                                                                                                               

18            while ( gradeCounter <= 5 ) {  // loop 5 times                                                                            

19                                                                                                                                                                                 

20               // prompt for input and read grade from user                                                                           

21               grade = JOptionPane.showInputDialog(                                                                                    

22                  "Enter integer   mark of grade: " );                                                                                        

23               gradeValue = Integer.parseInt( grade );         // convert grade from a String to an integer

24               total = total + gradeValue;   // add gradeValue to total                                                        

25               gradeCounter = gradeCounter + 1; // add 1 to gradeCounter                                               

26            }  // end while structure                                                                                                                     

27            average = total / 10;  // perform integer division                                                                        

28                                                                                                                                                                                 

29            // display average of exam grades                                                                                                    

30            JOptionPane.showMessageDialog( null,                                                                                        

31               " Average   =  " + average, "Average Class ",                                                                         

32               JOptionPane.INFORMATION_MESSAGE );                                                                         

33                                                                                                                                                                                 

34             System.exit( 0 );     // terminate the program                                                                             

35         }  // end method main                                                                                                                             

36      }  // end class Average1                                                                                                                              

 

ตัวอย่างโปรแกรม : รับค่าตัวเลขโดยให้  User ป้อนตัวเลขไปเรื่อย ๆ ไม่จำกัดจำนวนรอบ  เมื่อ Userต้องการจบการทำงานให้ป้อนเลข 0    และแสดงผลรวม (sum) ของตัวเลขทั้งหมดที่ป้อนเข้าไป

 

 

 

 

 

 

 

 

Output:

 

ch3_03

 

Source Code:

1        // Ans1.java                                                                                   

2        import javax.swing.JOptionPane;                                           

3                                                                                                                  

4        public class Ans1 {                                                                     

5            public static void main( String args[] )                           

6           {                                                                                                   

7              int sum=0,          // sum                                                    

8              check;                                                               

9               String  i,a;      

10                                                                                                               

11            // Initialization Phase                                                          

12             i = JOptionPane.showInputDialog(                               

13                 "Please Enter Number and Endter 0 to Quit : " );

14            check = Integer.parseInt(i);                                              

15                                                                                                                

16      sum  += check;                                                                             

17      while ( check != 0 ) {                                                               

18      i = JOptionPane.showInputDialog(                                       

19                  "Please Enter Number and Endter 0 to Quit : " );

20      check = Integer.parseInt(i);                                                    

21      sum  += check;    // add gradeValue to total                      

22      }  // end while                                                                              

23                                                                                                               

24        // display average of exam grades                                        

25            JOptionPane.showMessageDialog( null,                       

26               "sum =  " + sum, "end of program",                         

27               JOptionPane.INFORMATION_MESSAGE );       

28                                                                                                                

29             System.exit( 0 );     // terminate the program            

30         }  // end method main                                                            

31      }  // end class Ans1                                                                     

                                                     

ตัวอย่างโปรแกรม :  การใช้ลูป while ในการวาดเส้นตรง ใน Java Applet

Output:

ch3_10

Source Code:

 

 

1        //  WhileDL.java                                                                                                         

2        import java.awt.Graphics;                                                                                        

3        import javax.swing.JApplet;                                                                                    

4                                                                                                                                                 

5        public class WhileDL extends JApplet {                                                              

6           public void paint( Graphics g )    // draw lines on applet’s background

7           {                                                                                                                                   

8              super.paint( g ); // call inherited version of method paint                       

9              int counter = 1;             // initialization                                                       

10                                           int x1=10,y1=10;                                                                  

11                                           int x2=300,y2=10;                                                                

12           while ( counter <= 20 ) {    // 20 line                                                           

13              g.drawLine(x1,y1,x2,y2);                                                                            

14              ++counter;                // increment                                                             

15                                                  x1+=10; y1+=10; x2+=10;y2+=10;                        

16           }  // end while                                                                                                      

17        }  // end method paint                                                                                            

18     }  // end class WhileCounter                                                                                    

          

           Run  ดูผลลัพธ์โดยใช้  IE Browser

 

การใช้คำสั่ง  break   และ   continue

บ่อยครั้งที่คุณทำงานกับกลุ่มคำสั่ง  Selection  (if, switch..case)  และ Repetition (for, do..while, while) ที่ต้องมี  2  คำสั่งนี้ใช้งานร่วมด้วยระหว่าง Code ของโปรแกรม ซึ่ง 2 คำสั่งดังกล่าวมีความหมายและการใช้งานดังนี้

 

break :   ใช้เพื่อหยุดการทำงานและออกจากโปรแกรมย่อย   เช่น ใช้จบการทำงานของ

case แต่ละ case   หรือใช้จบการทำงานของ  loop

continue :  ใช้เพื่อสั่งให้เครื่องทำต่องานต่อ  หรือให้ขึ้นไปวนรอบของ loop

 

ตัวอย่างโปรแกรม:  การใช้คำสั่ง  break   ภายในโปรแกรม

Output:

 

 

ch3_08

 

Source Code:

1         // BreakSTM.java                                                   

2         import javax.swing.JOptionPane;                      

3         public class BreakSTM {                                     

4            public static void main( String args[] )       

5            {                                                                              

6               String output = "";                                         

7               int count;                                                          

8               for ( count = 1; count <= 6; count++ ) {

9                  if ( count == 3 )                                         

10                   break;  // break loop only if count == 3

11                   output += count + " ";                          

12             }  // end for                                                     

13             output += "\n  loop  count = " + count;  

14             JOptionPane.showMessageDialog( null, output);

15             System.exit( 0 );  // terminate application

16          }  // end method main                                       

17       }  // end classBreakSTM                                      

 

 

 

 

ตัวอย่างโปรแกรม:  การใช้คำสั่ง  continue   ภายในโปรแกรม

Output:

 

ch3_09

 

Source Code:

1               // ContinueSTM.java                                                                                                                                                               

2               import javax.swing.JOptionPane;                                                                                                                                        

3                                                                                                                                                                                                                     

4               public class ContinueSTM {                                                                                                                                                 

5                  public static void main( String args[] )                                                                                                                          

6                  {                                                                                                                                                                                                

7                     String output = "";                                                                                                                                                           

8                                                                                                                                                                                                                     

9                     // loop 6 times                                                                                                                                                                   

10                  for ( int count = 1; count <= 6; count++ ) {                                                                                                            

11                         if ( count == 3 ) // if count is 5, continue with next iteration of loop

12                                        continue;  // skip remaining code in loop                                     only if count == 3                                  

13                      output += count + " ";                                                                                                                                               

14                  }  // end for                                                                                                                                                                        

15                  output += "\ncontinue to skip 3";                                                                                                                                

16                  JOptionPane.showMessageDialog( null, output );                                                                                                  

17                                                                                                                                                                                                                   

18                  System.exit( 0 );  // terminate application                                                                                                                 

19               } // end  main()                                                                                                                                                                     

20            }  // end class ContinueSTM                                                                                                                                                 

     

แบบฝึกหัดท้ายบทที่ 3

 

ตอนที่ 1  :   อธิบายโปรแกรม  เขียน Output  หรือเขียนโปรแกรมตามที่โจทย์กำหนด

 

1) จงเขียน Output ของโปรแกรมต่อไปนี้  

 

1                   // Cmp.java                                                                                        

2                   import javax.swing.JOptionPane;                                               

3                   public class Cmp{                                                                           

4                      public static void main( String args[] )                                 

5                      {                                                                                                       

6                         String first,second,result;                                                    

7                         int num1,num2;                                                                     

8                         first =  JOptionPane.showInputDialog( "Enter num#1    " );

9                                                                                                                                 

10                       second =                 JOptionPane.showInputDialog( "Enter  num#2  " );

11                       num1 = Integer.parseInt( first );                                         

12                       num2 = Integer.parseInt( second );                                    

13                       result = "";                                                                                

14                       if ( num1 == num2 )                                                              

15                          result = num1 + " == " + num2;                                     

16                                                                                                                              

17                       if ( num1 != num2 )                                                               

18                          result = num1 + " != " + num2;                                      

19                                                                                                                              

20                       if ( num1 < num2 )                                                                 

21                          result = result + "\n" + num1 + " < " + num2;

22                                                                                                                              

23                       if ( num1 > num2 )                                                                 

24                          result = result + "\n" + num1 + " > " + num2;

25                                                                                                                              

26                       if ( num1 <= num2 )                                                              

27                          result = result + "\n" + num1 + " <= " + num2;

28                                                                                                                              

29                       if ( num1 >= num2 )                                                              

30                          result = result + "\n" + num1 + " >= " + num2;

31                                                                                                                              

32                       JOptionPane.showMessageDialog(                                     

33                          null, result, "Results   =   ",                                             

34                          JOptionPane.INFORMATION_MESSAGE );

35                       System.exit( 0 );                                                                     

36                                                            }                                                               

37                 }                                                                                                           

 

2 )  จงเขียน Output ของโปรแกรมและอธิบายคำสั่งโปรแกรมในแต่ละบรรทัด

 

1        // SumFor.java                                                                             

2        import javax.swing.JOptionPane;                                           

3        public class SumFor {                                                                

4           public static void main( String args[] )                             

5           {                                                                                                   

6              int sum = 0;                                                                           

7                 for ( int num = 2; num <= 50; num += 2 )             

8                 sum += num;                                                                    

9              JOptionPane.showMessageDialog( null, "sum =    " + sum,

10               "Sum number  from   2  - 50",                                   

11               JOptionPane.INFORMATION_MESSAGE );       

12            System.exit( 0 );                                                                 

13         }                                                                                                   

14      }                                                                                                       

 

3)  เขียนโปรแกรมรับค่าคะแนนและคำนวณเกรด ตามเงื่อนไขดังต่อไปนี้

                0-49                       F

                50-59                     D

                60-69                     C

                70-79                     B

                80-100                   A

                หากป้อนเกินตัวเลขเกิน 100   หรือต่ำกว่า  0  ให้มี Message แจ้ง Error

 

4 )   เขียนโปรแกรมรับค่าตัวเลข หากค่าที่รับเข้ามานั้น หารด้วย 2 แล้วเศษเท่ากับ 0 ให้แสดงข้อความ

"The number is Even"  แต่ถ้าไม่ใช่ให้แสดงข้อความ "The number is Odd"  โดยใช้  Dialog  ของ JOptionPane ในการรับค่าและแสดงผล

 

5 )  จงเขียนโปรแกรมรับค่า “แม่ของสูตรคูณ”  จาก User  จะนั้นคำนวณและแสดงผลลัพธ์ของสูตรคูณ

6 )  เขียนโปรแกรมรับค่าตัวเลข   โดยให้  User  ระบุจำนวนรอบที่ต้องการทำซ้ำ  จากนั้นคำนวณหาผลรวม(sum)   ค่าเฉลี่ย(Average)  และ นับจำนวนรอบ (Count)    

7. จงเขียนโปรแกรมสามารถรับค่าตัวเลขได้เรื่อย ๆ เมื่อ User  ต้องการจบการทำงาน  ให้ป้อนเลข  0   จากนั้นแสดงข้อความ “Bye..Bye..End of Program”

 

ตอนที่ 2:  จงเติมคำที่ขาดหายไปลงในช่องว่าง

1)  เครื่องหมาย               เริ่มต้น  body  ของ  method  และใช้เครื่องหมาย             เพื่อสิ้นสุด  bodyของ  

     method

2)  การเขียนประโยค  statement  ต้องจบด้วยเครื่องหมาย                    .              

3)  คำสั่ง               ใช้ในการตัดสินใจเลือกทำงานอย่างมีเงื่อนไข

4)  เครื่องหมาย                  ใช้สำหรับสร้างประโยคหมายเหตุ  1 บรรทัด

5)  Class                     จะบรรจุ  methods ที่สามารถแสดงข่าวสารใน  dialogs ได้

6)                       เป็นความสงวนในภาษา Java

7)  Java applications  จะเริ่มต้นทำงานที่   method                  .

8)  Methods                                             และ                                      ใช้แสดงผลข้อข้อมูลออกทาง

      หน้าต่าง  command window

9)                         method  การเรียกใช้จะต้องเชื่อมด้วยเครื่องหมาย  dot (.)

 

ตอนที่ 3: (True/False) จงเติม T  หน้าข้อที่คิดว่าถูกต้อง  และเติม   F  หน้าข้อที่คิดว่าผิด

1)  ....... การใช้ประโยคหมายเหตุ  จะทำให้คอมพิวเตอร์  Print ข้อความที่อยู่หลังเครื่องหมาย print  //   

              ออกทางหน้าจอเมื่อสั่ง Run โปรแกรม

2)  .......การประกาศตัวแปรจะต้องประกาศพร้อมกับระบุชนิดข้อมูลที่จะใช้

3)  .......Java   จะมองว่าตัวแปรชนิดตัวเลข (variables number)  กับข้อมูลตัวเลขนั้นเหมือนกัน

4)  .......การใช้เครื่องหมาย    modulus operator (%)   สามารถใช้ได้กับข้อมูลชนิด integer เท่านั้น

5)  .......เครื่องหมายคำนวณทางคณิตศาสตร์ (arithmetic operators)  ประกอบด้วย *,  /,  %,  +  และ  -   

             ซึ่งทั้งหมดนี้มีลำดับในการคำนวณสำคัญเท่ากัน

6)  .......Method “Integer.parseInt”  จะใช้แปลงข้อมูล integer   ให้เป็นข้อมูลชนิด   String

 

ตอนที่ 4: จงเขียนประโยคคำสั่งของ Java  (Java statements)  ตามโจทย์ต่อไปนี้

1)  ประกาศตัวแปร  c, thisIsAVariable, q76354  โดยใช้ข้อมูลชนิด  int

2)  แสดง dialog  ถาม User ให้ป้อนข้อมูลตัวเลขเข้ามาในกล่อง dialog

3)  แปลงข้อมูล  String   ให้เป็นข้อมูลชนิด  integer  และเก็บข้อมูลนั้นไว้ในตัวแปรชื่อ  age

4)  ถ้าตัวแปรชนิดตัวเลขมีค่าไม่เท่ากับ  7  ให้แสดงข้อความ  "The variable number is not equal to 7"  

      ออกทางหน้าจอโดยใช้กล่อง dialog

5)  แสดงข้อความ  "This is a Java program"  จำนวน 1 บรรทัดออกทางหน้าต่าง  command window

6)  แสดงข้อความ "This is a Java program"  โดยแบ่งข้อความให้เป็น  2  บรรทัดแต่เขียนให้อยู่ในคำสั่ง

      บรรทัดเดียว  แสดงผลทางหน้าจอ  command window

 

ตอนที่ 5 :  จงค้นหาข้อผิดพลาด (Error)  ของโปรแกรมต่อไปนี้  และอธิบายถึงสาเหตุที่ผิด

1)  while (c <= 5) {

product *= c;

++c;

 

2)  if (gender ==1)

System.out.println ("Woman");

Else;

        System.out.println ("Man");

 

3)  While (z >= 0)

                                Sum += z;

 

 

copy right @ ณัฎภัทรศญา ทับทิมเทศ, "การเขียนโปรแกรมเชิงวัตถุ”, 2552

 

บรรณานุกรม

H.M.Deital Deitel &Associates,Inc., P.J.Deitel Deitel&Associates,Inc, " Java  How
to Program 4th", Prentice Hall,USA,2002         
http://www.netbeans.org/kb/50/index.html
http://java.sun.com/docs/books/tutorial/uiswing/index.html

http://java.sun.com/docs/books/tutorial/uiswing/components/components.html
http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/JComponent.html
http://java.sun.com/docs/books/tutorial/uiswing/TOC.html
Help, Netbeans 5.0, 2006

www.No-Poor.com

Java,จาวา,การเขียนโปรแกรมภาษา Java,กิฟฟารีน,giffarine,บทเรียนคอมพิวเตอร์,ไอที,IT,กรณีศึกษา,สื่อการสอน,โปรเจ็ค,project