在switch条件语句和循环语句中都可以使用break语句。当break语句出现在switch条件语句中时,其作用是终止某个case并向下执行;当barak语句出现在循环语句中时,其作用是跳出循环语句,执行后面的代码。下面通过案例实现输出1~5之间的自然数,当值为4时,使用break语句跳出循环,如文件2-8所示。

  文件2-8  Example08.java

package com.itheima.example;
public class Example08 {
    public static void main(String[] args){
        int x=1;
        while (x <= 5) {
            System.out.println("x="+x);
            if (x == 4){
                break;
            }
            x++;
        }
    }
}

运行结果如图2-16所示。

Java的break语句

 

 图2-16  运行结果

  在文件2-8中,通过while循环输出x的值,当x的值为4时,使用break语句跳出循环。因此结果中并没有出现x=5.

相关文章:

  • 2021-05-07
  • 2022-12-23
  • 2022-12-23
  • 2021-08-01
  • 2021-12-21
  • 2021-10-12
  • 2021-07-20
  • 2021-06-20
猜你喜欢
  • 2022-12-23
  • 2021-11-09
  • 2021-09-07
  • 2021-05-25
  • 2022-12-23
  • 2021-04-28
  • 2022-12-23
相关资源
相似解决方案