码迷,mamicode.com
首页 > 其他好文 > 详细

00016_跳转语句break

时间:2017-12-21 01:55:45      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:结果   class   []   流程   出现   print   body   实现   ==   

1、跳转语句的概念

    跳转语句用于实现循环执行过程中程序流程的跳转,在Java中的跳转语句有break语句和continue语句

2、break语句

  (1)在switch条件语句和循环语句中都可以使用break语句

  (2)当它出现在switch条件语句中时,作用是终止某个case并跳出switch结构

  (3)当它出现在循环语句中,作用是跳出循环语句,执行后面的代码

3、当变量x的值为3时,使用break语句跳出循环

 1 public class BreakDemo {
 2     public static void main(String[] args) {
 3         int x = 1; // 定义变量x,初始值为1
 4         while (x <= 4) { // 循环条件
 5             System.out.println("x = " + x); // 条件成立,打印x的值
 6             if (x == 3) {
 7                 break;
 8             }
 9             x++; // x进行自增
10         }
11     }
12 }

  在上述带代码中,通过while循环打印x的值,当x的值为3时使用break语句跳出循环。因此打印结果中并没有出现“x=4”

4、标记

  当break语句出现在嵌套循环中的内层循环时,它只能跳出内层循环,如果想使用break语句跳出外层循环则需要对外层循环添加标记

 1 public class BreakDemo02 {
 2     public static void main(String[] args) {
 3         int i, j; // 定义两个循环变量
 4            a: for (i = 1; i <= 9; i++) { // 外层循环
 5             for (j = 1; j <= i; j++) { // 内层循环
 6                 if (i > 4) { // 判断i的值是否大于4
 7                     break itcast; // 跳出外层循环
 8                 }
 9                 System.out.print("*"); // 打印*
10             }
11             System.out.print("\n"); // 换行
12         }
13     }
14 }

 

00016_跳转语句break

标签:结果   class   []   流程   出现   print   body   实现   ==   

原文地址:http://www.cnblogs.com/gzdlh/p/8076390.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!