java中for break的用法_java break语句的使用方法

在switch语中,break语句用来终止switch语句的执行。使程序 switch语句后的第一个语句 开始执行。

在Java中,可以为每个代码块加一个括号,一个代码块通常 用大括号{}括起来的一段 代码。加标号的格式

break语句有两种形式:无标签和有标签。无标签的break语句用来跳出单层switch、for、while、or do-while 循环,而有标签的break语句则用来跳出嵌套的switch、for、while、or do-while语句。

BlockLabel:{codeBlock}

调出while

public class MainClass {

public static void main(String[] args) {

int i = 0;

while (true) {

System.out.println(i);

i ;

if (i > 3) {

break;

}

}

}

}

终止for循环

public class MainClass {

public static void main(String[] args) {

int count = 50;

for (int j = 1; j < count; j ) {

if (count % j == 0) {

System.out.println("Breaking!!");

break;

}

}

}

}

双重循环

public class Main {

public static void main(String args[]) {

int len = 100;

int key = 50;

int k = 0;

out: {

for (int i = 0; i < len; i ) {

for (int j = 0; j < len; j ) {

if (i == key) {

break out;

}

k = 1;

}

}

}

System.out.println(k);

}

}

更复杂的

public class MainClass {

public static void main(String[] args) {

OuterLoop: for (int i = 2;; i ) {

for (int j = 2; j < i; j ) {

if (i % j == 0) {

continue OuterLoop;

}

}

System.out.println(i);

if (i == 37) {

break OuterLoop;

}

}

}

}

2

3

5

7

11

13

17

19

23

29

31

37


版权声明:本文为weixin_42193786原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。