-----------android培训、java培训、java学习型技术博客、期待与您交流!------------
java中几种常见的循环。
1:switch循环
int x = 11;
switch(x){
case 1:
case 2:
case 3:
System.out.println("小");
break;
case 4:
case 5:
case 6:
System.out.println("中");
break;
case 7:
//case 8:
//case 9:
System.out.println("大");
break;
default:
System.out.println("无");
break;
}
当X的值都不符合case条件时程序会执行default块的语句。
注意的是X的参数类型只能是short、byte、char、int、Enum
2:while循环
while循环分为两种
|-----while
int x = 11;
while(x<10)
{
System.out.println(x);
x++;
}
此时程序不会运行 while先判断条件不符合就不会在往下走了。
|-----do...while
int x = 11;
do
{
System.out.println(x);
}while(x<10);
此时程序会执行一次,因为do...while是先执行在判断条件。
总结:while的两种循环 while最少不执行,do...while至少执行一次。
3:for循环
for(int x=0;x<10;x++)
{
System.out.println(x);
}
下边是for循环的一个特殊写法的例子 输出结果是acbcb
for(System.out.println("a");y<3;System.out.println("b")){
System.out.println("c");
y++;
}
原理首先先执行System.out.println("a") ,在判断y<3,如果y<3则执行System.out.println("b"),之后跳入到循环里执行System.out.println("c")和y++,跳出循环继续判断y<3,如果y<3则执行System.out.println("b")如此往复。
System.out.println("a")只在第一判断条件时执行一次,以后都不会在执行了。
for循环的特例-----增强型for循环(jdk1.5之后)
增强for循环
格式: for(数据类型 变量名 :被遍历的集合(Collection)或者数组){}
格式: for(数据类型 变量名 :被遍历的集合(Collection)或者数组){}
int[] arr = {1,2,3,5,7};
for(int a : arr)
{
System.out.println(a);
}
传统for和增强for循环的区别:
增强for有一个局限性,必须有被遍历的目标,建议在遍历数组时还是用传统的for循环。
增强for有一个局限性,必须有被遍历的目标,建议在遍历数组时还是用传统的for循环。