ในเรื่อง switch ... case เราเคยเจอการใช้งาน break เพื่อออกจากคำสั่ง switch มาแล้ว บทความนี้แนะนำการใช้ break เพิ่มเติมเมื่อใช้กับ Control statement แบบทำซ้ำ นักพัฒนาอาจเรียกการทำซ้ำอีกชื่อหนึ่งว่า ลูป (loop)
break ถูกนำมาใช้เพื่อออกจาก loop เมื่อเข้าเงื่อนไขที่เราต้องการ
ตัวอย่างการใช้งาน break กับ for
Source Code
public class Break {
public static void main(String args[]) {
int count; // กำหนดตัวแปร count สำหรับนับจำนวนรอบ
for (count = 1; count <= 20; count++) { // loop ของ for
if (count == 11) // ถ้า count มีค่าเป็น 11 คำสั่ง break; ภายใน if จะทำงาน
break; // ออกจาก loop และไม่ทำคำสั่งด้านล่างต่อ
System.out.printf("%d ", count);
}
System.out.printf("\nBroke out of loop at count = %d\n", count);
}
}
Output
1 2 3 4 5 6 7 8 9 10
Broke out of loop at count = 11
ตัวอย่างการใช้งาน break กับ while
Source Code
public class Break {
public static void main(String args[]) {
int count = 1; // กำหนดตัวแปร count สำหรับนับจำนวนรอบ
while (count <= 20) { // loop ของ while
if (count == 11) // ถ้า count มีค่าเป็น 11 คำสั่ง break ภายใน if จะทำงาน
break; // ออกจาก loop และไม่ทำคำสั่งด้านล่างต่อ
System.out.printf("%d ", count); // แสดงค่าตัวแปร count ออกหน้าจอ
count++;
}
System.out.printf("\nBroke out of loop at count = %d\n", count);
}
}
Output
1 2 3 4 5 6 7 8 9 10
Broke out of loop at count = 11
คำสั่ง continue ใช้เพื่อต้องการเริ่มต้นรอบใหม่ของ loop โดยไม่สนใจคำสั่งที่เหลือ
ตัวอย่างการใช้งาน continue กับ while
Source Code
public class Continue {
public static void main(String args[]) {
for (int count = 1; count <= 20; count++) {
if (count == 11) // ถ้า count มีค่าเป็น 11 คำสั่ง continue ภายใน if จะทำงาน
continue; // เริ่มต้นรอบใหม่โดยไม่สนใจคำสั่งที่เหลือด้านล่าง
System.out.printf("%d ", count); // แสดงค่าตัวแปร count ออกหน้าจอ
}
System.out.println("\nUsed continue to skip printing 11");
}
}
Output
1 2 3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20
Used continue to skip printing 11
บทความถัดไป