คำสั่ง continue ใน Java ใช้ข้ามการทำงานของรอบปัจจุบันในลูป (for หรือ while) และไปรอบถัดไปทันที ไม่ได้หยุดลูปทั้งหมดเหมือน break
รูปแบบการใช้งาน
continue;
มักใช้ร่วมกับ if เพื่อตรวจสอบเงื่อนไขก่อนตัดสินใจข้ามรอบ
ตัวอย่างที่ 1: คำนวณเกรดนักเรียน (ข้ามนักเรียนขาดสอบ)
class CalculateTestScores {
public static void main(String[] args) {
String[] students = {"Mark", "Bill", "Lucy", "Chloe"};
int[] grades = {16, 25, 0, 19};
for (int i = 0; i < students.length; ++i) {
if (students[i].equals("Lucy")) {
continue; // ข้าม Lucy ไปรอบถัดไปทันที
}
if (grades[i] > 17) {
System.out.println(students[i] + " has passed with grade " + grades[i]);
} else {
System.out.println(students[i] + " has failed with grade " + grades[i]);
}
}
}
}
ผลลัพธ์:
Mark has failed their test with the grade 16. Bill has passed their test with the grade 25. Chloe has passed their test with the grade 19.
Lucy ถูกข้าม ไม่แสดงผล
ตัวอย่างที่ 2: เกมคูณตัวเลข (ข้ามเลขมากกว่า 10)
import java.util.Scanner;
class MathGame {
public static void main(String[] args) {
int total = 1;
Scanner input = new Scanner(System.in);
for (int i = 0; i < 3; ++i) {
System.out.print("Enter a number: ");
int number = input.nextInt();
if (number > 10) {
continue; // ข้ามการคูณถ้าเลข > 10
}
total = total * number;
}
System.out.println("Total = " + total);
}
}
กรอก 2, 5, 11 → Total = 10 (เพราะ 11 ถูกข้าม)
Labelled continue Statement
ใช้ข้ามไปยังลูปชั้นนอก (outer loop) โดยระบุ label:
outerLoop:
while (true) {
while (true) {
if (condition) {
continue outerLoop; // ข้ามไปรอบถัดไปของ outer loop
}
}
}
ความแตกต่าง break vs continue
| คำสั่ง | การทำงาน |
|---|---|
break | หยุดลูปทั้งหมด ทันที |
continue | ข้ามรอบปัจจุบัน ไปรอบถัดไป |
สรุป
continue ช่วยควบคุมลูปให้ยืดหยุ่น ข้ามบางรอบได้ตามเงื่อนไข โดยไม่ต้องหยุดโปรแกรมทั้งหมด