在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所示。
图2-16 运行结果
在文件2-8中,通过while循环输出x的值,当x的值为4时,使用break语句跳出循环。因此结果中并没有出现x=5.