Java 继续语句

Java 连续语句用于跳过循环的当前迭代,在 java 中,继续语句可以用作,同时做循环。

Java 继续声明

当连续语句用于嵌入循环时,它只会跳过内部循环的当前执行。Java连续语句可以用标签来跳过外环的当前迭代。

Java 继续为 loop

假设我们有一个整数的数组( / 社区 / 教程 / 初始化 - 数组 - Java),我们只想处理整数,在这里我们可以使用连续循环来跳过偶数的处理。

 1package com.journaldev.java;
 2
 3public class JavaContinueForLoop {
 4
 5    public static void main(String[] args) {
 6    	int[] intArray = { 1, 2, 3, 4, 5, 6, 7 };
 7
 8    	// we want to process only even entries
 9    	for (int i : intArray) {
10    		if (i % 2 != 0)
11    			continue;
12    		System.out.println("Processing entry " + i);
13    	}
14    }
15
16}

java continue statement, java continue for loop

Java在循环时继续

假设我们有一个数组,我们只想处理由3分割的索引数。

 1package com.journaldev.java;
 2
 3public class JavaContinueWhileLoop {
 4
 5    public static void main(String[] args) {
 6    	int[] intArray = { 0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };
 7    	int i = 0;
 8    	while (i < 10) {
 9
10    		if (i % 3 != 0) {
11    			i++;
12    			continue;
13    		}
14    		System.out.println("Processing Entry " + intArray[i]);
15    		i++;
16    	}
17    }
18
19}

java while loop continue

Java 继续做-而循环

我们可以轻松地替换上方的循环代码以下方的循环代码,继续陈述的结果和效果将与上方的图像相同。

1do {
2
3    if (i % 3 != 0) {
4    	i++;
5    	continue;
6    }
7    System.out.println("Processing Entry " + intArray[i]);
8    i++;
9} while (i < 10);

Java 继续标签

我们将在本示例中使用 [两个维度数组]( / 社区 / 教程 / 两个维度数组 - Java)并仅处理一个元素,如果所有元素都是正数。

 1package com.journaldev.java;
 2
 3import java.util.Arrays;
 4
 5public class JavaContinueLabel {
 6
 7    public static void main(String[] args) {
 8
 9    	int[][] intArr = { { 1, -2, 3 }, { 0, 3 }, { 1, 2, 5 }, { 9, 2, 5 } };
10
11    	process: for (int i = 0; i < intArr.length; i++) {
12    		boolean allPositive = true;
13    		for (int j = 0; j < intArr[i].length; j++) {
14    			if (intArr[i][j] < 0) {
15    				allPositive = false;
16    				continue process;
17    			}
18    		}
19    		if (allPositive) {
20    			// process the array
21    			System.out.println("Processing the array of all positive ints. " + Arrays.toString(intArr[i]));
22    		}
23    		allPositive = true;
24    	}
25
26    }
27
28}

java continue label

Java 继续保持重要点

关于 java 连续声明的一些重要点是;

对于简单的案例来说,连续陈述可以很容易地被 if-else 条件取代,但当我们有多个 if-else 条件时,使用连续陈述使我们的代码更易于读取 2.连续陈述有助于嵌入循环,并跳过某个特定记录的处理

我已经制作了一个简短的视频,详细解释了java继续声明,你应该在下面观看。 https://www.youtube.com/watch?v=udqWkqhc2kw 参考: Oracle 文档

Published At
Categories with 技术
Tagged with
comments powered by Disqus