Java แบ่ง
คำสั่ง break ใน Java ส่วนใหญ่จะใช้ในสองกรณีต่อไปนี้- ตัวแบ่งออกจากลูปและกระโดดออกจากลูป (ทั้งสำหรับและในขณะที่)
- คำสั่ง break ออกจากกรณีและปัญหาในคำสั่ง switch
ไวยากรณ์
break;
ตัวอย่าง
public class Driver1 {
public static void main(String[] args) {
// Testing break statement in while loop
System.out.println("Test Break statement in While loop");
int i = 0;
while (i < 5) {
if (i == 2) {
break;
}
System.out.println(i++);
}
}
}
เอาต์พุต
ทดสอบคำสั่ง Break ใน while ลูป 0 1
Java ดำเนินการต่อ
คำสั่งดำเนินการต่อในภาษาจาวามักใช้กับกรณีต่อไปนี้- โดยจะข้ามคำสั่งต่อไปนี้และย้ายไปยังการวนซ้ำถัดไปในfor loop
- ดำเนินการต่อในขณะที่วนซ้ำคำสั่งต่อไปนี้และข้ามไปที่คำสั่งเงื่อนไข
ไวยากรณ์
continue;
ตัวอย่าง
public class Driver2 {
public static void main(String[] args) {
// Testing continue statement in while loop
System.out.println("Test Continue in While loop");
int i = 0;
while (i < 5) {
if (i == 2) {
i++;
continue;
}
System.out.println(i++);
}
}
}
เอาต์พุต
ทดสอบดำเนินการต่อในขณะที่ลูป 0 1 3 4
ความแตกต่างระหว่างดำเนินการต่อและทำลาย
ความแตกต่างอย่างมากระหว่างการหยุดและดำเนินการต่อคือการที่การหยุดออกจากลูปในครั้งเดียว เมื่อดำเนินการคำสั่ง break แล้ว ลูปจะไม่ทำงานอีก อย่างไรก็ตาม หลังจากดำเนินการคำสั่งดำเนินการต่อแล้ว บรรทัดของโค้ดต่อไปนี้จะถูกข้ามสำหรับการวนซ้ำปัจจุบันเท่านั้น ลูปจะเริ่มดำเนินการอีกครั้งหยุดและดำเนินการต่อในขณะที่วนซ้ำ
สามารถใช้ Break และ Continue ได้ทั้งสองแบบในลูปwhile ลองดูตัวอย่างด้านล่างเพื่อความเข้าใจที่ชัดเจนตัวอย่าง
public class Driver {
public static void main(String[] args) {
// Testing both break and continue statements side by side
String [] weekdays = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
System.out.println("Test Break statement in While loop");
System.out.println("\nWorking Days:\n");
int i = 0;
while (i < weekdays.length ) {
if (weekdays[i].equals("Saturday") || weekdays[i].equals("Sunday")) {
i++;
break;
// Not any working day will be printed
// because the loop breaks on Sunday
// once the loop breaks it moves out of the loop
}
System.out.println(weekdays[i++]);
}
System.out.println("\nTest Continue statement in While loop");
System.out.println("\nWorking Days:\n");
int j = 0;
while (j < weekdays.length ) {
if (weekdays[i].equals("Saturday") || weekdays[i].equals("Sunday")) {
j++;
continue;
// All the working/business days will be printed
// when the loop encounters Saturday or Sunday
// it skips that iteration and continues to the next iteration
}
System.out.println(weekdays[i++]);
}
// A test case for continue statement using for loop
System.out.println("\nTest Continue in For loop");
for (int x = 0; x < 5; x++) {
if (x == 2)
continue;
System.out.println(x);
}
}
}
เอาต์พุต
ทดสอบคำสั่งพักในลูป while วันทำงาน: ทดสอบคำสั่งต่อในลูป while วันทำงาน: จันทร์ อังคาร พุธ พฤหัสบดี ศุกร์ ทดสอบต่อในลูป 0 1 3 4
GO TO FULL VERSION