break、continue
- break在任何循环语句的主体部分,均可用break控制循环的流程。break用于强行退出循环,不执行循环中剩余的语句。(break语句也在switch语句中使用)
- continue语句用在循环语句体中,用于终止某次循环过程,即跳过循环体中尚未执行的语句,接着进行下一次是否执行循环的判定。
- 关于goto关键字
- goto关键字很早就在程序设计语言中出现。尽管goto仍是Java的一个保留字,但并未在语言中得到正式使用;Java没有goto。然而,在break和continue这两个关键字的身上,我们仍然能看出一些goto的影子---带标签的break和continue。
- “标签”是指后面跟一个冒号的标识符,例如: label:
- 对Java来说唯一用到标签的地方是在循环语句之前。而在循环之前设置标签的唯一理由是:我们希望在其中嵌套另个循环,由于break和continue关键字通常只中断当前循环,但若随同标签使用,它们就会中断到存在标签的地方。
break
package com.lemon.struct;
public class BreakDemo {
public static void main(String[] args) {
int i = 0;
while (i<100){
i++;
System.out.print(i+"\t");
if(i==30){
break;
}
}
System.out.println("123");
}
}
//运行结果
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
123
Process finished with exit code 0
continue
package com.lemon.struct;
public class ContinueDemo {
public static void main(String[] args) {
int i = 0;
while (i<100){
i++;
if(i%10==0){
System.out.println();
continue;
}
System.out.print(i+"\t");
}
}
}
//运行结果
1 2 3 4 5 6 7 8 9
11 12 13 14 15 16 17 18 19
21 22 23 24 25 26 27 28 29
31 32 33 34 35 36 37 38 39
41 42 43 44 45 46 47 48 49
51 52 53 54 55 56 57 58 59
61 62 63 64 65 66 67 68 69
71 72 73 74 75 76 77 78 79
81 82 83 84 85 86 87 88 89
91 92 93 94 95 96 97 98 99
Process finished with exit code 0
package com.lemon.struct;
public class LabelDemo {
public static void main(String[] args) {
//打印101~150之间所有的质数
//质数是指大于1的自然数中,除了1和它本身以外不再有其他因素的自然数
int count = 0;
//不建议使用
outer:for (int i = 101;i<150;i++){
for (int j=2;j<i/2;j++){
if (i%j==0) {
continue outer;
}
}
System.out.println(i+" ");
}
}
}
//运行结果
101
103
107
109
113
127
131
137
139
149
Process finished with exit code 0
练习
package com.lemon.struct;
public class TestDemo01 {
public static void main(String[] args) {
//打印一个5行的三角形
for (int i = 1; i <= 5; i++) {
for(int j=5;j>=i;j--){
System.out.print(" ");
}
for (int j=1;j<=i;j++){
System.out.print("*");
}
for (int j=1;j<i;j++){
System.out.print("*");
}
System.out.println();
}
}
}
//运行结果
*
***
*****
*******
*********
Process finished with exit code 0