break和continue

阅读量: 1005 编辑

一、break 和 continue 关键字

breakcontinue 常常用在循环表达式中,可以放在任何位置,比如 switch 中的 break,就是跳出当前正在执行的 case 语句;

break 是直接跳出总循环,就是说循环不再执行了;

continue 是跳出当次循环,就是当次循环结束,然后 "继续" 下一次循环;

二、编程实战

代码的详细解读,可以参考视频教程

/**
 * User: 祁大聪
 */
public class C25 {

    public static void main(String[] args) {

        //跑步10圈
        int totalCount = 10;
        int count = 0;
        while(count < totalCount){
            if(count == 5){
                break; //break之后,while将不再执行
            }
            System.out.println("跑了第" + (count+1) + "圈");
            count++;
        }


        System.out.println("-----------------------------");
        
        //重新赋值
        count = 0;
        while(count < totalCount){
            if(count == 5){
                count++;
                
                // count==5这次,后面的代码不会再执行,而是直接进行count==6的循环
                continue;
            }
            System.out.println("跑了第" + (count+1) + "圈");
            count++;
        }

    }
}

爱码岛编程公众号
试卷资料
爱码岛编程小程序
在线刷题
苏ICP备13052010号
©2023 南京匠成信息科技有限公司