1、break
break:作用于循环中,表示跳出当前循环
做实验:while(true){ System.out.println("111"); System.out.println("222"); if(true){ break; } System.out.println("333"); }
案例:循环录入张三同学5门课的成绩并计算平均分, 如果某分数录入为负,停止录入并提示。
public static void main(String[] args){ Scanner scan = new Scanner(System.in); double sum = 0; boolean flag = true; for(int i = 1;i<=5;i++){ System.out.println("请输入第" + i + "门成绩:"); double score = scan.nextDouble(); if(score < 0){ flag = false; break; } sum += score; } if(flag){ double avg = sum/5; System.out.println("平均分为:" + avg); }else{ System.out.println("输入的分数为负数,停止录入");
2、continue
continue:作用于循环中,表示跳过当前循环体剩余的部分,进入到下一次循环
做实验:while(true){ System.out.println("111"); System.out.println("222"); if(true){ continue; } System.out.println("333"); }
案例:循环录入Java课5名学生的成绩,统计分数大于等于80分的学生比例。
解决方案1: Scanner scan = new Scanner(System.in); int count = 0;//分数大于等于80分学生的个数 for(int i = 1;i<=5;i++){ System.out.println("请输入第" + i + "名学生的成绩:"); double score = scan.nextDouble(); if(score >= 80){ count++; } } double proportion = count/5.0*100; System.out.println("分数大于等于80分学生的比例为:" + proportion + "%");
解决方案2:————运用continue Scanner scan = new Scanner(System.in); int count = 0;//分数大于等于80分学生的个数 for(int i = 1;i<=5;i++){ System.out.println("请输入第" + i + "名学生的成绩:"); double score = scan.nextDouble(); if(score < 80){ continue; } count++; } double proportion = count/5.0*100; System.out.println("分数大于等于80分学生的比例为:" + proportion + "%");
3、return
return:作用于方法中,表示解决当前方法
public static void main(String[] args){ System.out.println("111"); System.out.println("222"); if(true){ return; } System.out.println("333");
4、 label
label的技术点—— label 它的作用:给循环做标记(取名字)
应用场景:可以在复杂的循环中,由内层循环结束掉指定循环
需求:嵌套for循环,外层循环6次,内层循环3次
当外层循环到第4次时,在内层循环中结束掉外层循环
1 -- 1
1 -- 2
1 -- 3
2 -- 1
2 -- 2
2 -- 3
3 -- 1
3 -- 2
3 -- 3
4 -- 1public static void main(String[] args){ a:for(int i = 1;i<=6;i++){ for(int j = 1;j<=3;j++){ System.out.println(i + " -- " + j); if(i == 4){ break a;//结束掉指定循环 } } } }