Java continue 语句

Java continue語句用於跳過循環的當前迭代。在Java中,continue語句可以與forwhiledo-while循環一起使用。

Java continue語句

當在嵌套循環中使用continue語句時,它只會跳過內部循環的當前執行。Java continue語句還可以與標籤一起使用,以跳過外部循環的當前迭代。讓我們來看一些continue java語句的示例。

Java continue for循環

假設我們有一個整數數組,我們只想處理偶數,這裡我們可以使用continue循環來跳過奇數的處理。

package com.journaldev.java;

public class JavaContinueForLoop {

	public static void main(String[] args) {
		int[] intArray = { 1, 2, 3, 4, 5, 6, 7 };

		// 我們只想處理偶數條目
		for (int i : intArray) {
			if (i % 2 != 0)
				continue;
			System.out.println("Processing entry " + i);
		}
	}

}

Java continue while循環

假設我們有一個數組,我們只想處理被3除的索引號,我們可以在這裡使用Java continue語句與while循環。

package com.journaldev.java;

public class JavaContinueWhileLoop {

	public static void main(String[] args) {
		int[] intArray = { 0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };
		int i = 0;
		while (i < 10) {

			if (i % 3 != 0) {
				i++;
				continue;
			}
			System.out.println("Processing Entry " + intArray[i]);
			i++;
		}
	}

}

Java continue do-while loop

我們可以輕易地將上述 while 迴圈程式碼替換為以下的 do-while 迴圈。continue 陳述式的結果和效果將與上面的圖片相同。

do {

	if (i % 3 != 0) {
		i++;
		continue;
	}
	System.out.println("Processing Entry " + intArray[i]);
	i++;
} while (i < 10);

Java continue 標籤

讓我們來看一個 Java continue 標籤的例子,以跳過外部迴圈的處理。我們在這個例子中將使用二維陣列,只有當所有元素都是正數時才處理一個元素。

package com.journaldev.java;

import java.util.Arrays;

public class JavaContinueLabel {

	public static void main(String[] args) {

		int[][] intArr = { { 1, -2, 3 }, { 0, 3 }, { 1, 2, 5 }, { 9, 2, 5 } };

		process: for (int i = 0; i < intArr.length; i++) {
			boolean allPositive = true;
			for (int j = 0; j < intArr[i].length; j++) {
				if (intArr[i][j] < 0) {
					allPositive = false;
					continue process;
				}
			}
			if (allPositive) {
				// 處理陣列
				System.out.println("Processing the array of all positive ints. " + Arrays.toString(intArr[i]));
			}
			allPositive = true;
		}

	}

}

Java continue 的重要要點

有關 Java continue 陳述式的一些重要要點是:

  1. 對於簡單的情況,可以輕鬆將 continue 陳述式替換為 if-else 條件,但當我們有多個 if-else 條件時,使用 continue 陳述式使得我們的程式碼更易讀。
  2. 在巢狀迴圈和跳過特定記錄的處理時,continue 陳述式非常方便。

I have made a short video explaining java continue statement in detail, you should watch it below. https://www.youtube.com/watch?v=udqWkqhc2kw Reference: Oracle Documentation

Source:
https://www.digitalocean.com/community/tutorials/java-continue-statement