Java loop control statement

Loop control contains two aspects. On the one hand, it controls how the loop variable changes. On the other hand, it needs to use two keywords break and continue to control the jump of the loop. The jump effects of these two jump statements are different. , Break is to interrupt the loop, continue is to execute the next loop.
1. Break statement
In the loop structure, you can use the break statement to jump out of the current loop body, thereby interrupting the current loop. Sample code:

public class Demo3 {
	public static void main(String[] args) {
		for (int i = 0; i < 10; i++) {
			System.out.println("i="+i);
			//当i=5时跳出循环
			if(i==5){
				break;
			}
		}
	}
}

Screenshot of the running result:
Insert picture description here
If you encounter the break statement in the inner loop, the break statement will only make the program jump out of the inner loop structure and will not affect the outer loop. Sample code:

for (int i = 0; i < 3; i++) {
	for (int j = 0; j <5; j++) {
		if(j==3){//当j=3时跳出内层循环
			break;
		}
		System.out.println("i="+i+",j="+j+";");
	}
}

Screenshot of the running result:
Insert picture description here
If you need to use break to jump out of the outer loop, you can use "label" to achieve it. The label name can be any identifier. The syntax is as follows:
label name: loop body { brake label name; } Sample code:


closure:for (int i = 0; i < 3; i++) {
	for (int j = 0; j < 6; j++) {
		if(j==5){
			break closure;//跳出closure标签标记的循环体
		}
		System.out.println("i="+i+",j="+j+";");
	}
}

Screenshot of the running results:
Insert picture description here
2. The
continue statement The continue statement is a supplement to the break statement. The continue statement does not jump out of the loop body immediately, but skips the statement before the end of the loop, returns to the conditional test part of the loop, and restarts the loop. Sample code:

for (int i = 1; i < 10; i++) {
	if(i%2 !=0){//如果i为奇数时跳到下一循环
		continue;
	}
	System.out.println("i="+i);
}

Screenshot of the running result:
Insert picture description here
Like the break statement, continue also supports the label function and the syntax structure is the same. Sample code:

completion:for (int i = 0; i < 5; i++) {
	for (int j = 1; j < 3; j++) {
		if(i==2 || i==3){
			continue completion;
		}
		System.out.println("i="+i+"j="+j+";");
	}
}

Screenshot of running result:
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_44547592/article/details/97146337