在Java中,顺序结构只能被执行一次,所以如果想要重复执行多次,就需要用到循环结构;Java中主要有三种循环结构:
while循环;
do...while循环;
for循环;
在java5中又引入了一种主要用于数组的增强型for循环。
1、while循环:先判断,后循环,只要布尔表达式为true,就会一直执行下去。
while循环结构:
while(布尔表达式){
//循环语句内容
}
实例:
public class Test {
public static void main(String[] args) {
int x = 10;
while( x < 15 ) {
System.out.println("value of x : " + x );
x++;
}
}
}
运行结果:
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
2、do...while循环:先循环,后判断,相对于while循环来说,do...while循环至少执行一次循环内容。
do...while循环结构:
do{
//循环内容
}while(布尔表达式);
实例:
public class Test {
public static void main(String[] args) {
int x = 10;
do {
System.out.println("value of x : " + x );
x++;
}
while( x < 15 ) ;
}
}
运行结果:
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
3、for循环:虽然所有的循环结构都可以用while和do...while循环表示,但Java提供了另一种循环语句,是一些循环结构变得简单。for循环的次数是在执行之前就确定的,for循环结构:
for(初始化;布尔表达式;更新){
//循环体代码
}
实体:
public class Test {
public static void main(String[] args) {
System.out.println("水仙花数有:");
int a,b,c;
for (int i=100;i<1000;i++) {
a=i/100;
b=i%100/10;
c=i%10;
if((a*a*a+b*b*b+c*c*c)==i)
System.out.println(i);
}
//九九乘法表
System.out.println("九九乘法表:");
for(int i=1;i<10;i++) {
for(int j=1;j<=i;j++) {
System.out.print(j+"x"+i+"="+j*i+"\t");
}
System.out.println();
}
}
}
运行结果:
水仙花数有:
153
370
371
407
九九乘法表:
1x1=1
1x2=2 2x2=4
1x3=3 2x3=6 3x3=9
1x4=4 2x4=8 3x4=12 4x4=16
1x5=5 2x5=10 3x5=15 4x5=20 5x5=25
1x6=6 2x6=12 3x6=18 4x6=24 5x6=30 6x6=36
1x7=7 2x7=14 3x7=21 4x7=28 5x7=35 6x7=42 7x7=49
1x8=8 2x8=16 3x8=24 4x8=32 5x8=40 6x8=48 7x8=56 8x8=64
1x9=9 2x9=18 3x9=27 4x9=36 5x9=45 6x9=54 7x9=63 8x9=72 9x9=81
4、增强for循环(for...each循环)
循环结构:
for(声明语句 : 表达式){
//循环体代码
}
实例:
public class Test {
public static void main(String[] args) {
int [] list= {1,2,3,4,5,6,7,8,9,10};
for(int x:list) {
System.out.println(x);
}
}
}
运行结果:
1
2
3
4
5
6
7
8
9
10
5、关键字
break关键字:
break 主要用在循环语句或者 switch 语句中,用来跳出整个语句块。
break 跳出最里层的循环,并且继续执行该循环下面的语句。
实例:
public class Test {
public static void main(String[] args) {
int [] list= {1,2,3,4,5};
for(int x:list) {
if(x==3) {
break;
}
System.out.println(x);
}
}
}
运行结果
1
2
continue关键字:
continue 适用于任何循环控制结构中。作用是让程序立刻跳转到下一次循环的迭代。
在 for 循环中,continue 语句使程序立即跳转到更新语句。
在 while 或者 do…while 循环中,程序立即跳转到布尔表达式的判断语句。
实例:
public class Test {
public static void main(String[] args) {
int [] list= {1,2,3,4,5};
for(int x:list) {
if(x==3) {
continue;
}
System.out.println(x);
}
}
}
运行结果:
1
2
4
5