CodeGym /Java Blog /Toto sisi /Java 中的中斷和繼續語句
John Squirrels
等級 41
San Francisco

Java 中的中斷和繼續語句

在 Toto sisi 群組發布

Java 中斷

Java中的break語句主要用於以下兩種情況。
  1. Break 退出循環並跳出循環(for 和 while)。
  2. Break 語句退出 switch 語句中的一個 case。

句法


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 循環中的 Test Break 語句 0 1

Java 繼續

Java中的continue語句常用於以下情況。
  1. 它跳過以下語句並移至for循環中的下一次迭代。
  2. 在 while 循環中繼續跳轉以下語句並跳轉到條件語句。

句法


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

continue 和 break 的區別

break 和 continue 之間的顯著區別在於 break 立即退出循環。一旦執行了 break 語句,循環將不會再次運行。但是,在執行 continue 語句後,將僅針對當前迭代跳過以下代碼行。循環將再次開始執行。

在 While 循環中中斷並繼續

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 循環中測試 Break 語句工作日:在 While 循環中測試 Continue 語句工作日:週一周二週三週四周五週五在 For 循環中測試 Continue 0 1 3 4

結論

那是 Java 中 break 與 continue 的簡單實現。希望通過以上示例的幫助,您可以了解何時使用什麼。我們鼓勵您練習以更好地學習。另外,請隨時向我們發布您可能有的任何反饋或問題。直到下一次,繼續學習並繼續成長。
留言
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION