break: 中断的意思 中断当前循环
* 使用场景:switch语句
* 循环中
* 注意:离开了使用场景单独存在无效
如下:
package com.yupy04;
public class BreakDemo {
public static void main(String[] args) {
//在控制台上输出10次helloworld
for(int i=1;i<=10;i++){
System.out.println("helloworld");
}
}
}
以上输出10次helloworld后,如果要求执行第三次循环时停止结束,那么:
package com.yupy04;
public class BreakDemo {
public static void main(String[] args) {
//在控制台上输出10次helloworld
for(int i=1;i<=10;i++){
//执行第三次循环时停止
if(i==3){
break;
}
System.out.println("helloworld");
}
}
}
加上一个判断条件语句 Break中断停止循环 此时在第三次循环时就停止,控制台只输出两次helloworld
continue:跳过当前这次循环,继续执行下一次循环
* 使用场景:循环语句中
* 注意:离开了使用场景没办法使用
如下:
package com.yupy04;
public class BreakDemo01 {
public static void main(String[] args) {
for(int i =1;i<=10;i++){
if(i == 5){ //随便在哪个地方停止结果一样,比如在5的一次循环停止,少了一次输出
continue; //因此,只输出9次helloworld 与Break不同
}
System.out.println("helloworld");
}
}
}
注意break和continue两者的区别:
1. 用法都相同,循环语句中添加判断条件
2. break是直接中断循环不继续执行后面的循环
continue是跳过当前循环不是立即停止循环后继续执行语句
3. 两者一样都不能除循环体外单独存在(无效使用)