ג'אווה ברייק
הצהרת Break ב-Java משמשת בעיקר בשני המקרים הבאים.- Break יוצא מהלולאה וקופץ ממנה (גם לזמן וגם לזמן).
- הצהרת הפסקה יוצאת ממקרה בהצהרת הבורר.
תחביר
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++);
}
}
}
תְפוּקָה
הצהרת הפסקת בדיקה ב-While loop 0 1
Java המשך
הצהרת continue ב-Java משמשת בדרך כלל במקרים הבאים.- הוא מדלג על ההצהרות הבאות ועובר לאיטרציה הבאה בלולאת for .
- המשך ב-while loops hop על ההצהרות הבאות וקפוץ להצהרה המותנית.
תחביר
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++);
}
}
}
תְפוּקָה
בדוק המשך בלולאת While 0 1 3 4
הבדלים בין המשך להפסקה
ההבדל המשמעותי בין הפסקה להמשך הוא שההפסקה יוצאת מלולאה בבת אחת. לאחר ביצוע הצהרת break, הלולאה לא תפעל שוב. עם זאת, לאחר ביצוע הצהרת continue, שורות הקוד הבאות ידלגו עבור האיטרציה הנוכחית בלבד. הלולאה תתחיל לפעול שוב.הפסקה והמשך ב-While Loop
ניתן להשתמש בשניהם ב- 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 loop ימי עבודה: הצהרת המשך בדיקה ב-While loop ימי עבודה: יום שני שלישי רביעי חמישי שישי מבחן המשך ב-For loop 0 1 3 4
GO TO FULL VERSION