转自:android.yaohuiji.com
Java中循环有三种形式 while循环、do-while循环 和 for循环。其中从Java 6 开始for循环又分 普通for循环 和 for-each循环两种,我们接下来分别讲解。
一、while 循环
当条件为真时执行while循环,一直到条件为假时再退出循环体,如果第一次条件表达式就是假,那么while循环将被忽略,如果条件表达式一直为真,那么while循环将一直执行。关于while 括号后的表达式,要求和if语句一样需要返回一个布尔值,用作判断是否进入循环的条件。
1 |
public class Lesson06_6 { |
2 |
public static void main(String[] args) { |
3 |
int x = 8 ; |
4 |
while (x > 0 ) { |
5 |
System.out.println(x); |
6 |
x--; |
7 |
} |
8 |
} |
9 |
} |
执行结果:
如果你把 x>0 改成大于8 ,while循环将一次都不执行
二、do-while 循环
好,如果你无论如何都想执行一次循环体内的代码,可以选择do-while循环,它的特点是做了再说。
1 |
public class Lesson06_6 { |
2 |
public static void main(String[] args) { |
3 |
int x = 8 ; |
4 |
do { |
5 |
System.out.println(x); |
6 |
x--; |
7 |
} while (x> 8 ); |
8 |
} |
9 |
} |
x=8,条件是大于8,查看运行结果,我们发现他总是会执行一次。
三、for 循环
当知道可以循环多少次时,是使用for循环的最佳时机。
1、基本for循环:
先举一个例子:
1 |
public class Lesson06_6 { |
2 |
public static void main(String[] args) { |
3 |
for ( int i = 2 , j = 1 ; j < 10 ; j++) { |
4 |
if (j >= i) { |
5 |
System.out.println(i + "x" + j + "=" + i * j); |
6 |
} |
7 |
} |
8 |
} |
9 |
} |
这个例子打印了从九九乘法表的一部分:
原谅我没有从最常用的for循环开始写,你把int i=2 写在for循环前面就变成最常用的for循环了。
下面说一下for循环的规则:
2、for-each循环:
for-each循环又叫增强型for循环,它用来遍历数组和集合中的元素,因此我们会在数组一章和集合一章里分别讲到,放心,你会掌握的很好。
这里举个例子给你看看先:
1 |
public class Lesson06_6 { |
2 |
public static void main(String[] args) { |
3 |
int [] a = { 6 , 2 , 3 , 8 }; |
4 |
for ( int n : a) { |
5 |
System.out.println(n); |
6 |
} |
7 |
} |
8 |
} |
运行结果如下:
四、跳出循环 break 、continue
break关键字用来终止循环或switch语句,continue关键字用来终止循环的当前迭代。当存在多层循环时,不带标签的break和continue只能终止离它所在的最内层循环,如果需要终止它所在的较外层的循环则必须用,标签标注外层的循环,并使用break和continue带标签的形式予以明确标示。
先看一个不带标签的例子BreakAndContinue.java:
01 |
public class BreakAndContinue { |
02 |
|
03 |
public static void main(String[] args) { |
04 |
|
05 |
int i = 0 ; |
06 |
while ( true ){ |
07 |
System.out.println( "i=" +i); |
08 |
if (i== 12 ){ |
09 |
i++; |
10 |
i++; |
11 |
continue ; |
12 |
} |
13 |
i++; |
14 |
if (i== 20 ){ |
15 |
break ; |
16 |
} |
17 |
} |
18 |
|
19 |
} |
20 |
|
21 |
} |
22 |
|
好例子自己会说话,这个例子打印了从1到20中除去13的数字。我们只需要看明白这个例子的输出结果就能明白break和continue的区别了。
编译并运行代码,查看结果:
我们再看一个break带标签的例子:
01 |
public class BreakAndContinue { |
02 |
|
03 |
public static void main(String[] args) { |
04 |
|
05 |
boolean isTrue = true ; |
06 |
outer: |
07 |
for ( int i= 0 ;i< 5 ;i++){ |
08 |
while (isTrue){ |
09 |
System.out.println( "Hello" ); |
10 |
break outer; |
11 |
} |
12 |
System.out.println( "Outer loop." ); |
13 |
} |
14 |
System.out.println( "Good Bye!" ); |
15 |
|
16 |
} |
17 |
|
18 |
} |
19 |
|
编译并运行程序,查看结果:
把上面的例子中break替换成continue,再次编译和运行,查看结果: