Java - Loop Control
ลูป (Loop) คือ ลักษณะการทำงานแบบวนซ้ำ ทำงานแบบเดิมไปเรื่อยๆ ในภาษา Java มี Loop อยู่ 3 รูปแบบ
· while Loop
· do...while Loop
· for Loop
while Loop
Syntax
while(Boolean_expression)
{
//Statements
}
คำสั่ง while loops จะทำการทดสอบเงื่อนไขก่อน ที่จะทำงาน ถ้าเงื่อนไขเป็นจริงจึงจะทำงานภายใน loop ถ้าเงือนไขไม่เป็นจริงจะไม่เข้าทำงาน
ตัวอย่าง เช่น
public class Test {
public static void main(String args[]) {
int x = 10;
while( x < 20 ) {
System.out.print("value of x " + x );
x++;
System.out.print("\n");
}
}
}
ผลการรัน
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19
do while Loop
Syntax
do
{
//Statements
}while(Boolean_expression);
คำสั่ง do while จะมีความแตกต่างจาก while loop ตรงที่คำสั่ง do while จะทำงานใน loop หนึ่งครั้งก่อนเสมอ ก่อนที่จะทำการทดสอบ
ตัวอย่าง
public class Test {
public static void main(String args[]){
int x = 10;
do{
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}while( x < 20 );
}
}
ผลการรัน
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19
for Loop
Syntax
for(initialization; Boolean_expression; update)
{
//Statements
}
initialization คือ กำหนดค่าเริ่มต้น
Boolean_expression คือ เงื่อนไขการทำงาน
update คือคำสั่งที่ใช้ในการเปลี่ยนค่าตัวแปร
คำสั่ง for จะเป็นการกำหนดจำนวนครั้งในการทำงานโดยจำนวนครั้งจะขึ้นอยู่กับตัวแปร index คือค่าของ index จะต้องตรงตามเงื่อนไขการทำงน
ตัวอย่าง
public class Test {
public static void main(String args[]) {
for(int x = 10; x < 20; x = x+1) {
System.out.print("value of x : " + x );
System.out.print("\n");
}
}
}
ผลการรัน
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19
จะเห็นว่าทั้ง 3 รูปแบบเป็นการทำงานซ้ำซึ่งให้ผลเหมือน กันเราสามารถเลือกใช้งานได้ตามความถนัดและความเหมาะสมของงาน